package com.getpebble.android.jskit.webapps;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.Toast;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Analytics.RemoteAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.appmessage.AppMessage;
import com.getpebble.android.framework.appmessage.AppMessage.AppMessageCommand;
import com.getpebble.android.jskit.HttpUtils;
import com.getpebble.android.jskit.JsAppPersistentSettings;
import com.getpebble.android.jskit.JsAppPersistentSettings.LaunchOnMessageSettingE;
import com.getpebble.android.jskit.JsInstalledApplicationInfo;
import com.getpebble.android.jskit.JsKitConstants;
import com.getpebble.android.jskit.bridge.AppMessageReceivedEvent;
import com.getpebble.android.jskit.bridge.DeviceBridge;
import com.getpebble.android.jskit.bridge.InstalledAppsBridge;
import com.getpebble.android.jskit.bridge.JsAppContextBridge;
import com.getpebble.android.jskit.bridge.JsAppInstaller;
import com.getpebble.android.jskit.bridge.JsDeveloperConnectionBridge;
import com.getpebble.android.jskit.bridge.TokenBridge;
import com.getpebble.android.jskit.concurrency.JsThreadPools;
import com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.WebappTypeE;
import com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled;
import com.sun.mail.smtp.SMTPMessage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsKit {
    protected static String ExtensionsPreparedDataString = makeExtensionsPreparedDataString();
    protected final long LAUNCH_WATCHDOG_TIMEOUT = 8000;
    protected AppMessageTIDTracker appMessageTIDTrackerInstance = new AppMessageTIDTracker();
    protected final Map<String, WebviewClientPack> mBuiltinWebviewClients = new HashMap();
    protected final Map<UUID, DelayedLaunchParams> mDelayedLaunchParamsMap = new HashMap();
    private Map<UUID, JsInstalledApplicationInfo> mInstalledApps = null;
    protected final Timer mJsAppHeartbeatVerifierTimer = new Timer(true);
    protected final AtomicReference<TimerTask> mJsAppHeartbeatVerifierTimerTask = new AtomicReference(null);
    protected final Map<UUID, Set<UUID>> mKillRecordKeeper = new HashMap();
    protected final AtomicInteger mKillRecordKeeperSizeBound = new AtomicInteger(2147483646);
    private UUID mLastRunningMessageUuid = null;
    Semaphore mLifecycleProcessingSequencer = new Semaphore(1);
    protected WeakReference<FragmentActivity> mMainActivityInstance = new WeakReference(null);
    protected final Map<UUID, Object[]> mPongSynchroWaitStatusMap = new HashMap();
    Map<UUID, List<AppMessageReceivedEvent>> mQueuedAppMessageReceivedEvents = new HashMap();
    Map<UUID, List<Object>> mQueuedJsEvents = new HashMap();
    protected Lock mStartupLaunchLock = new ReentrantLock();
    private Handler mTimeoutHandler = new Handler(Looper.getMainLooper());
    final Timer mWatchAppRequeryTimer = new Timer(true);
    protected WeakReference<PebbleWebappBaseActivity> mWebappBaseActivityInstance = new WeakReference(null);
    protected Map<Long, WeakReference<WebviewClientPack>> mWebappProcessTable = new HashMap();
    protected final Map<UUID, WebviewClientPack> mWebviewClients = new HashMap();
    protected Lock pebbleMainActivityInstanceAccessLock = new ReentrantLock();
    protected Lock pebbleWebappBaseActivityInstanceAccessLock = new ReentrantLock();

    static /* synthetic */ class AnonymousClass15 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE = new int[JsEventTypeE.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$TransactionManagement$TransactionType = new int[TransactionType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.AppMessageAck.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.AppMessageNack.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.AppMessageData.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.WebUiOk.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.WebUiOkSimpleForm.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.WebUiOpened.ordinal()] = 6;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.WebUiClosed.ordinal()] = 7;
            } catch (NoSuchFieldError e7) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$JsEventTypeE[JsEventTypeE.Ready.ordinal()] = 8;
            } catch (NoSuchFieldError e8) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$TransactionManagement$TransactionType[TransactionType.HttpGet.ordinal()] = 1;
            } catch (NoSuchFieldError e9) {
            }
            try {
                $SwitchMap$com$getpebble$android$jskit$webapps$JsKit$TransactionManagement$TransactionType[TransactionType.HttpPost.ordinal()] = 2;
            } catch (NoSuchFieldError e10) {
            }
        }
    }

    public static class AppMessageTIDTracker {
        protected Map<Byte, String> mTracker = new HashMap();

        public synchronized String sentMessage(String appUuidString, byte transactionId) {
            String str;
            if (appUuidString == null) {
                str = null;
            } else {
                str = (String) this.mTracker.get(Byte.valueOf(transactionId));
                this.mTracker.put(Byte.valueOf(transactionId), appUuidString);
            }
            return str;
        }

        public synchronized String ackNackReceived(byte transactionId) {
            return (String) this.mTracker.remove(Byte.valueOf(transactionId));
        }
    }

    protected static class DelayedLaunchParams {
        public final boolean ShowConfig;

        public DelayedLaunchParams(boolean showConfig) {
            this.ShowConfig = showConfig;
        }
    }

    public enum JsEventTypeE {
        _INVALID_,
        AppMessageAck("appmessage_ack"),
        AppMessageNack("appmessage_nack"),
        AppMessageData("appmessage"),
        WebUiOk("settings_webui_allowed"),
        WebUiOkSimpleForm("showConfiguration"),
        WebUiOpened("webviewopened"),
        WebUiClosed("webviewclosed"),
        Ready("ready");
        
        String ename;

        private JsEventTypeE(String en) {
            this.ename = en;
        }
    }

    private static class JsKitInstalledAppsLockRef {
        public static Lock INST = new ReentrantLock();
    }

    private static class JsKitRef {
        public static JsKit INST = new JsKit();
    }

    public static abstract class JsPIPCDeliveryAgentInstance implements Callable<JsPIPCDeliveryTaskTerminationData> {
        public String[] contextData;
        public UUID contextTarget;
        public final String id = UUID.randomUUID().toString();
        public WeakReference<JsPseudoIPCDeliveryTask> runner = null;
        public ConditionVariable synchroExecutionStartCV = new ConditionVariable();

        public static class JsPIPCDeliveryAgentInstanceTerminationData implements JsPIPCDeliveryTaskTerminationData {
            public final CauseOfTerminationE mCauseOfTermination = CauseOfTerminationE._INVALID_;
            public final Object[] mReturnDataAbstracts = new String[0];
        }

        protected abstract void execute();

        public void bindToRunner(JsPseudoIPCDeliveryTask jsPseudoIPCDeliveryTaskRunner) {
            if (jsPseudoIPCDeliveryTaskRunner != null && this.runner == null) {
                this.runner = new WeakReference(jsPseudoIPCDeliveryTaskRunner);
            }
        }

        public void setContextTarget(UUID uuid) {
            this.contextTarget = uuid;
        }

        public UUID getContextTarget() {
            return this.contextTarget == null ? new UUID(0, 0) : this.contextTarget;
        }

        public void setContextData(String d) {
            this.contextData = new String[]{d};
        }

        public String getContextData() {
            return (this.contextData != null && this.contextData.length > 0) ? this.contextData[0] : null;
        }

        protected void runDelayedConstruction() {
        }

        public boolean equals(Object o) {
            if (o instanceof JsPIPCDeliveryAgentInstance) {
                return this.id.equals(((JsPIPCDeliveryAgentInstance) o).id);
            }
            return false;
        }

        public int hashCode() {
            return this.id.hashCode();
        }

        protected boolean signalRunnerForStart() {
            try {
                ((JsPseudoIPCDeliveryTask) this.runner.get()).jsPIPCDeliveryAgentInstanceStart();
                return true;
            } catch (Exception e) {
                Trace.debug("JsKit", "signalRunnerForStart", e);
                return false;
            }
        }

        protected boolean signalRunnerForTermination(JsPIPCDeliveryTaskTerminationData retVal) {
            try {
                ((JsPseudoIPCDeliveryTask) this.runner.get()).jsPIPCDeliveryAgentInstanceTerminating(retVal);
                return true;
            } catch (Exception e) {
                Trace.debug("JsKit", "signalRunnerForTermination", e);
                return false;
            }
        }

        public JsPIPCDeliveryTaskTerminationData call() throws JsPIPCDeliveryAgentInstanceCallableException {
            this.synchroExecutionStartCV.block();
            signalRunnerForStart();
            runDelayedConstruction();
            JsPIPCDeliveryTaskTerminationData retVal = executeCall();
            signalRunnerForTermination(retVal);
            return retVal;
        }

        protected JsPIPCDeliveryTaskTerminationData executeCall() throws JsPIPCDeliveryAgentInstanceCallableException {
            execute();
            return new JsPIPCDeliveryAgentInstanceTerminationData();
        }

        public void startExecuting() {
            this.synchroExecutionStartCV.open();
        }
    }

    public static class JsPIPCDeliveryAgentInstanceCallableException extends Exception {
    }

    public static class JsPIPCWebappClosedEventDeliveryAgent extends JsPIPCDeliveryAgentInstance {
        protected void execute() {
            UUID originatingWebappId = null;
            try {
                originatingWebappId = UUID.fromString(getContextData());
            } catch (Exception e) {
                Trace.debug("JsKit", "JsPIPCWebappOpenedEventDeliveryAgent", e);
            }
            JsKit.jsKitAccess().signalWebappUiClosed(originatingWebappId, getContextTarget());
        }
    }

    public static class JsPIPCWebappOpenedEventDeliveryAgent extends JsPIPCDeliveryAgentInstance {
        protected void execute() {
            UUID originatingWebappId = null;
            try {
                originatingWebappId = UUID.fromString(getContextData());
            } catch (Exception e) {
                Trace.debug("JsKit", "JsPIPCWebappOpenedEventDeliveryAgent", e);
            }
            JsKit.jsKitAccess().signalWebappUiOpened(originatingWebappId, getContextTarget());
        }
    }

    public static class JsPseudoIPC {
        private JsKit mJsKitRef;
        Map<String, DataPieces<DataPiece>> mRepo;

        public static class DataPiece {
            public String Data;
            public String OptTag;

            public DataPiece(String opttag, String data) {
                set(opttag, data);
            }

            public DataPiece() {
                set(null, null);
            }

            public void set(String opttag, String data) {
                if (opttag == null) {
                    opttag = "";
                }
                this.OptTag = opttag;
                if (data == null) {
                    data = "";
                }
                this.Data = data;
            }
        }

        public static class DataPieces<E> extends ArrayList<E> {
            protected final int EXAMINE_WAIT = 0;
            protected final int RETRIEVE_WAIT = 1;
            protected Condition examineWaiter = null;
            protected Lock lock = null;
            protected boolean removeData = false;
            protected Condition retrieveWaiter = null;
            protected int[] waitCount = new int[]{0, 0};

            protected synchronized Lock assureLockRef() {
                if (this.lock == null) {
                    this.lock = new ReentrantLock();
                }
                return this.lock;
            }

            protected synchronized Condition[] assureConditionRefs() {
                Lock lockRef = assureLockRef();
                if (this.examineWaiter == null) {
                    this.examineWaiter = lockRef.newCondition();
                }
                if (this.retrieveWaiter == null) {
                    this.retrieveWaiter = lockRef.newCondition();
                }
                return new Condition[]{this.examineWaiter, this.retrieveWaiter};
            }

            public void add(int index, E obj) throws IndexOutOfBoundsException {
                Lock lockRef = assureLockRef();
                Condition[] condRefs = assureConditionRefs();
                lockRef.lock();
                try {
                    super.add(index, obj);
                    condRefs[0].signalAll();
                    condRefs[1].signalAll();
                    lockRef.unlock();
                } catch (IndexOutOfBoundsException e) {
                    lockRef.unlock();
                    throw e;
                }
            }

            public boolean add(E obj) {
                Lock lockRef = assureLockRef();
                Condition[] condRefs = assureConditionRefs();
                lockRef.lock();
                boolean rv = super.add(obj);
                condRefs[0].signalAll();
                condRefs[1].signalAll();
                lockRef.unlock();
                return rv;
            }

            public boolean addAll(Collection<? extends E> c) throws NullPointerException {
                Lock lockRef = assureLockRef();
                Condition[] condRefs = assureConditionRefs();
                lockRef.lock();
                try {
                    boolean rv = super.addAll(c);
                    if (rv) {
                        condRefs[0].signalAll();
                        condRefs[1].signalAll();
                    }
                    lockRef.unlock();
                    return rv;
                } catch (NullPointerException e) {
                    lockRef.unlock();
                    throw e;
                }
            }

            public boolean addAll(int index, Collection<? extends E> c) throws IndexOutOfBoundsException, NullPointerException {
                Lock lockRef = assureLockRef();
                Condition[] condRefs = assureConditionRefs();
                lockRef.lock();
                try {
                    boolean rv = super.addAll(index, c);
                    if (rv) {
                        condRefs[0].signalAll();
                        condRefs[1].signalAll();
                    }
                    lockRef.unlock();
                    return rv;
                } catch (NullPointerException e) {
                    lockRef.unlock();
                    throw e;
                } catch (IndexOutOfBoundsException e2) {
                    lockRef.unlock();
                    throw e2;
                }
            }
        }

        private static class JsPseudoIPCRef {
            public static JsPseudoIPC INST = new JsPseudoIPC();
        }

        public static JsPseudoIPC systemInstanceAccess() {
            return JsPseudoIPCRef.INST;
        }

        private JsPseudoIPC(int systemInstParam) {
            this.mRepo = new HashMap();
            this.mJsKitRef = JsKit.jsKitAccess();
        }

        private JsPseudoIPC() {
            this.mRepo = new HashMap();
        }

        public void leaveData(String idTag, String optTag, String data) {
            if (idTag != null) {
                DataPieces<DataPiece> node;
                synchronized (this.mRepo) {
                    node = (DataPieces) this.mRepo.get(idTag);
                }
                if (node == null) {
                    node = new DataPieces();
                    synchronized (this.mRepo) {
                        this.mRepo.put(idTag, node);
                    }
                }
                if (data != null) {
                    node.add(new DataPiece(optTag, data));
                }
            }
        }

        public String[] retrieveNextData(String idTag) {
            if (idTag == null) {
                return null;
            }
            synchronized (this.mRepo) {
                DataPieces<DataPiece> node = (DataPieces) this.mRepo.get(idTag);
            }
            if (node == null) {
                return null;
            }
            if (node.size() < 1) {
                return null;
            }
            node.lock.lock();
            DataPiece p = (DataPiece) node.remove(0);
            node.lock.unlock();
            return new String[]{p.OptTag, p.Data};
        }
    }

    public static class JsPseudoIPCDeliveryTask extends FutureTask<JsPIPCDeliveryTaskTerminationData> {
        public ExecStateE execState = ExecStateE.INVALID;
        public JsPIPCDeliveryTaskTerminationData storedReturnData;

        public interface JsPIPCDeliveryTaskTerminationData {
        }

        public enum CauseOfTerminationE {
            _INVALID_,
            SelfCompleted,
            Cancelled,
            SelfAborted
        }

        public enum ExecStateE {
            INVALID,
            ConstructedAlive,
            RunningAlive,
            CancelledDead,
            CompletedDead
        }

        public void jsPIPCDeliveryAgentInstanceStart() {
            synchronized (this.execState) {
                this.execState = ExecStateE.RunningAlive;
            }
        }

        public void jsPIPCDeliveryAgentInstanceTerminating(JsPIPCDeliveryTaskTerminationData retVal) {
            synchronized (this.execState) {
                this.execState = ExecStateE.CompletedDead;
                this.storedReturnData = retVal;
            }
        }

        public JsPseudoIPCDeliveryTask(JsPIPCDeliveryAgentInstance callable) {
            super(callable);
            callable.bindToRunner(this);
            this.execState = ExecStateE.ConstructedAlive;
        }
    }

    public enum SignalMessageTypeE {
        _INVALID_,
        Ack,
        Nack,
        Data
    }

    protected static class TransactionManagement {
        public static final ExecutorService executor = Executors.newFixedThreadPool(4);
        public Map<String, TransactionFutureTask> ExecutingTransactionMap = new HashMap();
        public Map<String, Transaction> TransactionMap = new HashMap();

        public static abstract class Transaction implements Callable<TransactionReturn> {
            public final String id = UUID.randomUUID().toString();
            public TransactionFutureTask runner = null;
            public ConditionVariable synchroExecutionStartCV = new ConditionVariable();

            public abstract TransactionReturn executeCall() throws TransactionCallableException;

            public void bindToRunner(TransactionFutureTask tftRunner) {
                if (tftRunner != null && this.runner == null) {
                    this.runner = tftRunner;
                }
            }

            public boolean equals(Object o) {
                if (o instanceof Transaction) {
                    return this.id.equals(((Transaction) o).id);
                }
                return false;
            }

            public int hashCode() {
                return this.id.hashCode();
            }

            public String key() {
                return this.id;
            }

            public TransactionReturn call() throws TransactionCallableException {
                this.synchroExecutionStartCV.block();
                if (this.runner != null) {
                    this.runner.transactionCallEntry();
                }
                TransactionReturn retVal = executeCall();
                if (this.runner != null) {
                    this.runner.transactionCallReturning(retVal);
                }
                return retVal;
            }

            public void startExecuting() {
                this.synchroExecutionStartCV.open();
            }
        }

        public static abstract class HttpTransaction extends Transaction {
            public final String url;

            public static class SimpleHttpTransactionReturn implements HttpTransactionReturn {
                public final ByteBuffer data;
                public final int httpCode;
                public final String transactionId;

                public SimpleHttpTransactionReturn() {
                    this.transactionId = "";
                    this.httpCode = 0;
                    this.data = ByteBuffer.wrap(new byte[0]);
                }

                public SimpleHttpTransactionReturn(String id, int code, byte[] d) {
                    this.transactionId = id;
                    this.httpCode = code;
                    this.data = d == null ? ByteBuffer.wrap(new byte[0]) : ByteBuffer.wrap(Arrays.copyOf(d, d.length));
                }
            }

            public HttpTransaction(String aUrl) {
                if (aUrl == null) {
                    aUrl = "";
                }
                this.url = aUrl;
            }
        }

        public static class HttpGetTransaction extends HttpTransaction {
            public HttpGetTransaction(String aUrl) {
                super(aUrl);
            }

            public HttpTransactionReturn executeCall() throws TransactionCallableException {
                Throwable th;
                try {
                    HttpURLConnection httpConnection = (HttpURLConnection) new URL(this.url).openConnection();
                    InputStream is = httpConnection.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int status = httpConnection.getResponseCode();
                    for (Entry<String, List<String>> header : httpConnection.getHeaderFields().entrySet()) {
                        new String(((String) header.getKey()) + "=" + header.getValue()).getBytes();
                    }
                    String charset = null;
                    for (String param : httpConnection.getHeaderField("Content-Type").replace(" ", "").split(";")) {
                        if (param.startsWith("charset=")) {
                            charset = param.split("=", 2)[1];
                            break;
                        }
                    }
                    if (charset != null) {
                        BufferedReader reader = null;
                        try {
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, charset));
                            while (true) {
                                try {
                                    String line = bufferedReader.readLine();
                                    if (line == null) {
                                        break;
                                    }
                                    byte[] b = line.getBytes();
                                    baf.append(b, 0, b.length);
                                } catch (Throwable th2) {
                                    th = th2;
                                    reader = bufferedReader;
                                }
                            }
                            if (bufferedReader != null) {
                                try {
                                    bufferedReader.close();
                                } catch (Throwable logOrIgnore) {
                                    Trace.debug("JsKit", "executeCall", logOrIgnore);
                                }
                            }
                        } catch (Throwable th3) {
                            th = th3;
                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (Throwable logOrIgnore2) {
                                    Trace.debug("JsKit", "executeCall", logOrIgnore2);
                                }
                            }
                            throw th;
                        }
                    }
                    return new SimpleHttpTransactionReturn(key(), status, baf.toByteArray());
                } catch (Exception e) {
                    throw new TransactionCallableException();
                }
            }
        }

        public interface TransactionReturn {
        }

        public interface HttpTransactionReturn extends TransactionReturn {
        }

        public static class TransactionCallableException extends Exception {
        }

        public static class TransactionFutureTask extends FutureTask<TransactionReturn> {
            public String callableId = "";
            public ExecState execState = ExecState.INVALID;
            public TransactionReturn storedReturnData = null;

            public enum ExecState {
                INVALID,
                ConstructedAlive,
                RunningAlive,
                CancelledDead,
                CompletedDead
            }

            public TransactionFutureTask(Transaction callable) {
                super(callable);
                callable.bindToRunner(this);
                this.execState = ExecState.ConstructedAlive;
            }

            public void transactionCallEntry() {
                synchronized (this.execState) {
                    this.execState = ExecState.RunningAlive;
                }
            }

            public void transactionCallReturning(TransactionReturn retVal) {
                synchronized (this.execState) {
                    this.execState = ExecState.CompletedDead;
                    this.storedReturnData = retVal;
                }
            }
        }

        public static class TransactionManagementRef {
            public static final TransactionManagement INST = new TransactionManagement();
        }

        public enum TransactionType {
            INVALID,
            HttpGet,
            HttpPost
        }

        protected TransactionManagement() {
        }

        public static TransactionManagement transactionManagement() {
            return TransactionManagementRef.INST;
        }

        public void executeTransaction(String tag) {
            Transaction t = (Transaction) this.TransactionMap.get(tag);
            if (t != null) {
                t.startExecuting();
            }
        }

        public String newTransaction(WebappRunHost initiator, TransactionType type, Object... args) {
            if (initiator == null) {
                return "";
            }
            Transaction nT = null;
            switch (AnonymousClass15.$SwitchMap$com$getpebble$android$jskit$webapps$JsKit$TransactionManagement$TransactionType[type.ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    nT = inHttpGet((String) args[0]);
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    nT = inHttpPost((String) args[1], (String[]) Arrays.copyOfRange(args, 1, args.length));
                    break;
            }
            if (nT == null) {
                return "";
            }
            if (this.TransactionMap.containsKey(nT.key())) {
                return "";
            }
            this.TransactionMap.put(nT.key(), nT);
            TransactionFutureTask nTT = new TransactionFutureTask(nT);
            this.ExecutingTransactionMap.put(nT.key(), nTT);
            executor.execute(nTT);
            return nT.key();
        }

        public String httpGet(WebappRunHost initiator, String url) {
            return newTransaction(initiator, TransactionType.HttpGet, url);
        }

        protected HttpTransaction inHttpGet(String url) {
            return new HttpGetTransaction(url);
        }

        protected HttpTransaction inHttpPost(String url, String[] kvPairs) {
            return null;
        }
    }

    public enum WebUiBringUpOpportunityTypeE {
        _INVALID_,
        any,
        settings,
        authentication
    }

    public static class WebviewClientPack {
        private boolean mClosing;
        public AtomicInteger mHeartbeatPeriodicCount;
        public boolean mIsBuiltIn;
        public PebbleBabel mMessageTranslatorForThisClient;
        public WebappProcessState mProcessState;
        public WebappRunHost mPromotedToPinnedRef = null;
        public Set<UUID> mSpawnedClients;
        public boolean mSuccessfulReadyCallbackExecuted;
        public boolean mUnkillable;
        public AtomicInteger mVerifyHeartbeatPeriodicCount;
        public Set<UUID> mWebappUuidsThatAttachedViaJsKitRegisterWebapp;
        public WeakReference<WebappRunHost> mWebviewClient;

        public enum WebappProcessState {
            INVALID,
            Unknown,
            Created,
            Dead,
            Running,
            Paused
        }

        public WebappRunHost getTempRef() {
            if (this.mWebviewClient != null) {
                return (WebappRunHost) this.mWebviewClient.get();
            }
            return null;
        }

        public WebviewClientPack(WebappRunHost wvclient) {
            init(wvclient, false, false, true);
        }

        protected void init(WebappRunHost wvclient, boolean pin, boolean isBuiltIn, boolean isKillable) {
            this.mWebviewClient = new WeakReference(wvclient);
            if (pin) {
                this.mPromotedToPinnedRef = wvclient;
            }
            this.mMessageTranslatorForThisClient = new PebbleBabel(wvclient.clientUuid());
            this.mProcessState = WebappProcessState.Unknown;
            this.mIsBuiltIn = isBuiltIn;
            this.mUnkillable = !isKillable;
            this.mSpawnedClients = new HashSet();
            this.mWebappUuidsThatAttachedViaJsKitRegisterWebapp = new HashSet();
            this.mSuccessfulReadyCallbackExecuted = false;
            this.mHeartbeatPeriodicCount = new AtomicInteger(Integer.MIN_VALUE);
            this.mVerifyHeartbeatPeriodicCount = new AtomicInteger(Integer.MIN_VALUE);
        }

        public WebviewClientPack setAttachedWebappUuidStringViaRegisterWebappCall(String webappUuidString) {
            try {
                this = setAttachedWebappUuidViaRegisterWebappCall(UUID.fromString(webappUuidString));
            } catch (Exception e) {
                Trace.debug("JsKit", "setAttachedWebappUuidStringViaRegisterWebappCall", e);
            }
            return this;
        }

        public WebviewClientPack setAttachedWebappUuidViaRegisterWebappCall(UUID webappUuid) {
            if (webappUuid != null) {
                this.mWebappUuidsThatAttachedViaJsKitRegisterWebapp.add(webappUuid);
            } else {
                Trace.debug("JsKit", "setAttachedWebappUuidViaRegisterWebappCall: webappUuid is null");
            }
            return this;
        }

        public boolean isWebappUuidOneOfAttached(UUID webappUuid) {
            try {
                return this.mWebappUuidsThatAttachedViaJsKitRegisterWebapp.contains(webappUuid);
            } catch (Exception e) {
                Trace.debug("JsKit", "isWebappUuidOneOfAttached", e);
                return false;
            }
        }

        public WebviewClientPack setAsBuiltIn() {
            this.mIsBuiltIn = true;
            return this;
        }

        public WebviewClientPack setAsImmortal() {
            this.mUnkillable = true;
            return this;
        }

        public boolean builtIn() {
            return this.mIsBuiltIn;
        }

        public void clearWebviewCache() {
            try {
                JsKit.runOnAvailableActivityUiThread((WebappRunHost) this.mWebviewClient.get(), new Runnable() {
                    public void run() {
                        try {
                            ((WebappRunHost) WebviewClientPack.this.mWebviewClient.get()).getWebView().clearCache(true);
                        } catch (Exception e) {
                            Trace.debug("JsKit", "clearWebviewCache", e);
                        }
                    }
                });
            } catch (Throwable e) {
                Trace.debug("JsKit", e);
            }
        }

        public boolean wasSuccessfulOnReadyCallbackExec() {
            return this.mSuccessfulReadyCallbackExecuted;
        }

        public void readyCallbackTouch() {
            this.mSuccessfulReadyCallbackExecuted = true;
        }

        public boolean verifyHeartbeatCount() {
            return verifyHeartbeatCount(4);
        }

        public boolean verifyHeartbeatCount(int threshold) {
            if (Math.abs(this.mHeartbeatPeriodicCount.get() - this.mVerifyHeartbeatPeriodicCount.incrementAndGet()) < ((Integer) JsKit.valueClamp(Integer.valueOf(0), Integer.valueOf(threshold), Integer.valueOf(100))).intValue()) {
                return true;
            }
            return false;
        }

        public int heartbeat() {
            return this.mHeartbeatPeriodicCount.incrementAndGet();
        }

        private void resyncSpawnedClientSet() {
            Iterator<UUID> it = this.mSpawnedClients.iterator();
            while (it.hasNext()) {
                if (JsKit.jsKitAccess().getWebappInfoByUuid((UUID) it.next()) == null) {
                    it.remove();
                }
            }
        }

        public void setNewSpawnedClient(UUID clientUuid) {
            synchronized (this.mSpawnedClients) {
                resyncSpawnedClientSet();
                if (clientUuid != null) {
                    this.mSpawnedClients.add(clientUuid);
                }
            }
        }

        public Set<UUID> getSpawnedClientsSetCopy() {
            Set hashSet;
            synchronized (this.mSpawnedClients) {
                resyncSpawnedClientSet();
                hashSet = new HashSet(this.mSpawnedClients);
            }
            return hashSet;
        }

        public UUID querySpawnedByOtherClient() {
            WebappRunHost hostRef;
            if (this.mWebviewClient != null) {
                hostRef = (WebappRunHost) this.mWebviewClient.get();
            } else {
                hostRef = null;
            }
            if (hostRef instanceof WebappGenericBaseFragment) {
                return ((WebappGenericBaseFragment) hostRef).queryCreatedByLinkedClient();
            }
            return null;
        }

        public UUID currentActiveAppUuid() {
            return currentActiveAppUuid(false);
        }

        public UUID currentActiveAppUuid(boolean strictAppUuidOnlyAndNullOtherwise) {
            if (this.mMessageTranslatorForThisClient != null) {
                return this.mMessageTranslatorForThisClient.currentActiveAppUuid(strictAppUuidOnlyAndNullOtherwise);
            }
            Trace.debug("JsKit", "currentActiveAppUuid: mMessageTranslatorForThisClient is null");
            return null;
        }

        public UUID clientUuid() {
            try {
                return ((WebappRunHost) this.mWebviewClient.get()).clientUuid();
            } catch (Exception e) {
                Trace.debug("JsKit", "clientUuid", e);
                return null;
            }
        }

        public Long getClientJsProcessId() {
            if (this.mWebviewClient != null) {
                WebappRunHost r = (WebappRunHost) this.mWebviewClient.get();
                if (r != null) {
                    return new Long(r.getWebappProcessId());
                }
                Trace.debug("JsKit", "getClientJsProcessId: r is null");
            }
            return Long.valueOf(0);
        }

        public boolean isClosing() {
            return this.mClosing;
        }

        public void setClosing() {
            this.mClosing = true;
        }

        public String toString() {
            return "isClosing = " + isClosing() + " clientUuid = " + clientUuid() + " currentActiveAppUuid = " + currentActiveAppUuid() + " mProcessState = " + this.mProcessState;
        }
    }

    public void newPebbleWebappBaseActivityInstanceCreated(PebbleWebappBaseActivity newInst) {
        if (newInst != null) {
            this.pebbleWebappBaseActivityInstanceAccessLock.lock();
            this.mWebappBaseActivityInstance = new WeakReference(newInst);
            this.pebbleWebappBaseActivityInstanceAccessLock.unlock();
        }
    }

    protected PebbleWebappBaseActivity getWebappBaseActivityTempRef() {
        this.pebbleWebappBaseActivityInstanceAccessLock.lock();
        PebbleWebappBaseActivity r = (PebbleWebappBaseActivity) this.mWebappBaseActivityInstance.get();
        this.pebbleWebappBaseActivityInstanceAccessLock.unlock();
        return r;
    }

    public FragmentActivity getMainActivityTempRef() {
        this.pebbleMainActivityInstanceAccessLock.lock();
        FragmentActivity r = (FragmentActivity) this.mMainActivityInstance.get();
        this.pebbleMainActivityInstanceAccessLock.unlock();
        return r;
    }

    public static Activity getAvailableActivityRef(WebappRunHost caller) {
        try {
            Activity aRef = (Activity) caller.getBackingContext();
            if (aRef != null) {
                return aRef;
            }
        } catch (Throwable e) {
            Trace.debug("getAvailableActivityRef", e);
        }
        return getAvailableActivityRef();
    }

    public static Activity getAvailableActivityRef() {
        return jsKitAccess().getMainActivityTempRef();
    }

    public static boolean runOnAvailableActivityUiThread(WebappRunHost caller, Runnable runnable) {
        Activity ref = getAvailableActivityRef(caller);
        if (ref != null) {
            try {
                ref.runOnUiThread(runnable);
                return true;
            } catch (Throwable e) {
                Trace.debug("runOnAvailableActivityUiThread", e);
                return false;
            }
        }
        new Handler(JsAppContextBridge.getInstance().getAppContext().getMainLooper()).post(runnable);
        return false;
    }

    public boolean handleSpecialUrlForWebViewLoadOverride(WebViewControlled view, URI urlToLoad) {
        if (view == null || urlToLoad == null) {
            Trace.debug("JsKit", "view or urlToLoad null");
            return false;
        }
        String hostPart = urlToLoad.getHost();
        String pathPart = urlToLoad.getPath();
        if (pathPart != null) {
            pathPart = pathPart.trim();
            while (pathPart.startsWith("/")) {
                if (pathPart.length() > 1) {
                    pathPart = pathPart.substring(1);
                } else {
                    pathPart = "";
                }
            }
        }
        String command = pathPart == null ? hostPart : pathPart.isEmpty() ? hostPart : pathPart;
        if (command == null) {
            Trace.info("JsKit", "No command");
            return false;
        } else if (!command.equals("close")) {
            return false;
        } else {
            UUID clientId = view.getOwnerClientId();
            if (isKnownJsAppClient(clientId)) {
                String tryParamDecode = null;
                try {
                    tryParamDecode = URLDecoder.decode(urlToLoad.getFragment(), "UTF-8");
                } catch (Exception e) {
                    Trace.info("JsKit", "URLDecoder.decode", e);
                }
                String parameters = tryParamDecode == null ? urlToLoad.getRawFragment() : tryParamDecode.isEmpty() ? urlToLoad.getRawFragment() : tryParamDecode;
                clientClose(clientId.toString(), parameters);
                return true;
            }
            Trace.info("JsKit", "!isKnownJsAppClient");
            return true;
        }
    }

    public WebResourceResponse handleLocalResourceLoadByWebapp(UUID ownerClientId, URI urlToLoad, String rawUrlStringAsRequestedByWebapp) {
        if (ownerClientId == null || urlToLoad == null) {
            Trace.debug("JsKit", "ownerClientId or urlToLoad null");
            return null;
        }
        String baseDirForWebapp = null;
        if (urlToLoad.getHost() == null) {
            baseDirForWebapp = determineBaseDirectoryForClientResourceLoad(ownerClientId, urlToLoad, rawUrlStringAsRequestedByWebapp);
        } else if (urlToLoad.getHost().equalsIgnoreCase("system")) {
            baseDirForWebapp = determineBaseDirectoryForSystemResourceLoad(ownerClientId, urlToLoad, rawUrlStringAsRequestedByWebapp);
        }
        if (baseDirForWebapp == null) {
            Trace.debug("JsKit", "baseDirForWebapp is null");
            return null;
        }
        URI loadableUri = null;
        try {
            if (urlToLoad.toString().contains(baseDirForWebapp)) {
                Trace.debug("JsKit", "jsdb urlToLoad contains baseDirForWebapp, so not appending");
                loadableUri = urlToLoad;
            } else {
                String str = "file";
                StringBuilder append = new StringBuilder().append("//").append(baseDirForWebapp.startsWith("/") ? "" : "/");
                if (baseDirForWebapp.endsWith("/")) {
                    baseDirForWebapp = baseDirForWebapp.substring(0, baseDirForWebapp.length() - 1);
                }
                loadableUri = new URI(str, append.append(baseDirForWebapp).append(urlToLoad.getRawPath()).toString(), urlToLoad.getRawFragment());
            }
        } catch (Throwable e) {
            Trace.debug("JsKit", e);
        }
        try {
            InputStream is = WebappSupport.inputStreamForResource(loadableUri.toString());
            if (is != null) {
                return new WebResourceResponse(HttpUtils.getMimeType(loadableUri.getPath().substring(loadableUri.getPath().lastIndexOf("/") + 1)), "", is);
            }
            Trace.debug("JsKit", "input stream is null");
            return null;
        } catch (Exception e2) {
            Trace.info("JsKit", "Error getting resource", e2);
            return null;
        }
    }

    protected String determineBaseDirectoryForClientResourceLoad(UUID ownerClientId, URI urlToLoad, String rawUrlStringAsRequestedByWebapp) {
        WebviewClientPack clientPack = getWebappInfoByUuid(ownerClientId);
        if (clientPack == null) {
            Trace.debug("JsKit", "Clientpack is null");
            return null;
        }
        String baseDirForWebapp = null;
        for (String tryClientMethod : new String[]{"direct", "linked"}) {
            if (tryClientMethod.equals("direct")) {
                try {
                    baseDirForWebapp = installedWebappsInfoForUuid(clientPack.currentActiveAppUuid()).getInstalledAbsPathOnFilesystem();
                } catch (Throwable e) {
                    Trace.debug("JsKit", e);
                }
            } else if (tryClientMethod.equals("linked")) {
                try {
                    UUID spawnedByLinkedClientUuid = clientPack.querySpawnedByOtherClient();
                    if (spawnedByLinkedClientUuid != null) {
                        baseDirForWebapp = installedWebappsInfoForUuid(getWebappInfoByUuid(spawnedByLinkedClientUuid).currentActiveAppUuid()).getInstalledAbsPathOnFilesystem();
                    }
                } catch (Throwable e2) {
                    Trace.debug("JsKit", e2);
                }
            }
            if (baseDirForWebapp != null) {
                return baseDirForWebapp;
            }
        }
        return baseDirForWebapp;
    }

    protected String determineBaseDirectoryForSystemResourceLoad(UUID ownerClientId, URI urlToLoad, String rawUrlStringAsRequestedByWebapp) {
        return "/android_asset/js_system_assets";
    }

    public void webViewOnPageFinished(WebViewControlled view, String urlString) {
        WebviewClientPack clientPack = getWebappInfoByUuid(view.getOwnerClientId());
        if (clientPack == null) {
            Trace.debug("JsKit", "clientPack is null");
            return;
        }
        try {
            WebappRunHost webappRef = (WebappRunHost) clientPack.mWebviewClient.get();
            if (webappRef != null && webappRef.lastUrlStringLoaded().equals(urlString)) {
                UUID linkedCreatedByClientId = null;
                try {
                    if (webappRef instanceof WebappGenericBaseFragment) {
                        linkedCreatedByClientId = ((WebappGenericBaseFragment) webappRef).queryCreatedByLinkedClient();
                        if (linkedCreatedByClientId != null) {
                            JsPIPCDeliveryAgentInstance mailman = new JsPIPCWebappOpenedEventDeliveryAgent();
                            mailman.setContextTarget(linkedCreatedByClientId);
                            mailman.setContextData(webappRef.clientUuidAsString());
                            JsThreadPools.MainWorkerThreadsExecutorService().execute(new JsPseudoIPCDeliveryTask(mailman));
                            mailman.startExecuting();
                            return;
                        }
                        Trace.debug("JsKit", "linkedCreatedByClientId is null");
                        return;
                    }
                    Trace.debug("JsKit", "Not a webui");
                } catch (Exception e) {
                    Trace.debug("JsKit", "queryCreatedByLinkedClient", e);
                }
            }
        } catch (Exception e2) {
            Trace.debug("JsKit", "webViewOnPageFinished", e2);
        }
    }

    private static Lock jsKitInstalledAppsLockAccess() {
        return JsKitInstalledAppsLockRef.INST;
    }

    public List<UUID> currentlyRunningJsApplications() {
        return currentlyRunningJsApplications(false, true);
    }

    public List<UUID> currentlyRunningJsApplications(boolean returnCurrentlyActiveJsAppUuids, boolean includeBuiltins) {
        List<UUID> rv = new ArrayList();
        synchronized (this.mWebappProcessTable) {
            List<Long> removeList = new ArrayList();
            for (Entry<Long, WeakReference<WebviewClientPack>> entry : this.mWebappProcessTable.entrySet()) {
                if (entry != null) {
                    if (entry.getValue() == null) {
                        removeList.add(entry.getKey());
                    } else {
                        WebviewClientPack tempRefV = (WebviewClientPack) ((WeakReference) entry.getValue()).get();
                        if (tempRefV == null) {
                            removeList.add(entry.getKey());
                        } else {
                            if (!includeBuiltins) {
                                try {
                                    if (tempRefV.builtIn()) {
                                    }
                                } catch (Exception e) {
                                    Trace.info("JsKit", "currentlyRunningJsApplications", e);
                                }
                            }
                            if (returnCurrentlyActiveJsAppUuids) {
                                rv.add(tempRefV.currentActiveAppUuid(true));
                            } else {
                                rv.add(((WebappRunHost) tempRefV.mWebviewClient.get()).clientUuid());
                            }
                        }
                    }
                }
            }
            for (Long k : removeList) {
                this.mWebappProcessTable.remove(k);
            }
        }
        return rv;
    }

    public void onSettingsLaunch(Context context, UUID appUUID) {
        JsAppContextBridge.getInstance().setAppContext(context);
        Trace.debug("JsKit", "onSettingsLaunch: UUID: " + appUUID);
        WebviewClientPack clientPack = jsKitAccess().getWebappInfoByUuid(appUUID);
        if (clientPack != null) {
            WebappRunHost hostClientObject = clientPack.mWebviewClient == null ? null : (WebappRunHost) clientPack.mWebviewClient.get();
            if (hostClientObject == null || !clientPack.getSpawnedClientsSetCopy().isEmpty()) {
                Trace.debug("JsKit", "onSettingsLaunch: hostClientObject is null or getSpawnedClientsSetCopy isEmpty");
            } else {
                jsKitAccess().signalOneWebappWebUiBringupOpportunity(WebUiBringUpOpportunityTypeE.settings, hostClientObject);
                return;
            }
        }
        Trace.debug("JsKit", "onSettingsLaunch: clientPack is null");
        JsInstalledApplicationInfo chkAppInfo = jsKitAccess().startWatchAppFromJsKitInternals(appUUID, true);
    }

    private void dumpCurrentJsApps() {
        synchronized (this.mWebviewClients) {
            Trace.debug("JsKit", "dumpCurrentJsApps:- (" + this.mWebviewClients.size() + ")");
            for (Entry<UUID, WebviewClientPack> ent : this.mWebviewClients.entrySet()) {
                Trace.debug("JsKit", " - UUID = " + ent.getKey() + ": " + ent.getValue());
            }
        }
    }

    public void onWatchAppStarted(Context context, UUID watchAppUuid) {
        Trace.verbose("JsKit", "onWatchAppStarted()");
        dumpCurrentJsApps();
        JsAppContextBridge.getInstance().setAppContext(context);
        this.mLifecycleProcessingSequencer.acquireUninterruptibly();
        onWatchAppStartedSequenced(watchAppUuid);
        this.mLifecycleProcessingSequencer.release();
    }

    private void onWatchAppStartedSequenced(UUID watchAppUuid) {
        jsKitAccess().launchInstanceOf(watchAppUuid, true);
    }

    public void onWatchAppStopped(Context context, UUID watchAppUuid) {
        this.mLifecycleProcessingSequencer.acquireUninterruptibly();
        onWatchAppStoppedSequenced(watchAppUuid);
        this.mLifecycleProcessingSequencer.release();
    }

    public void onWatchAppStoppedSequenced(UUID watchAppUuid) {
        if (watchAppUuid == null) {
            Trace.debug("JsKit", "onWatchAppStoppedSequenced: watchAppUuid is null");
            return;
        }
        Trace.debug("JsKit", "onWatchAppStoppedSequenced");
        this.mLastRunningMessageUuid = null;
        if (isKnownCurrentActiveJsApp(watchAppUuid)) {
            WebviewClientPack clientPack = getWebappInfoByUuid(watchAppUuid);
            if (clientPack == null) {
                Trace.debug("JsKit", "onWatchAppStoppedSequenced: clientPack is null");
            } else if (!clientPack.getSpawnedClientsSetCopy().isEmpty()) {
                Trace.debug("JsKit", "onWatchAppStoppedSequenced() for [" + watchAppUuid.toString() + "] is a " + "NO-Go. This instance has a webui spawned");
                return;
            }
            PebbleWebappBaseActivity.closeWebapp(jsKitAccess().getWebappBaseActivityTempRef(), watchAppUuid.toString(), WebappTypeE.NoUi);
            RemoteAppBehavior.logJsAppStopped(watchAppUuid.toString());
            return;
        }
        Trace.verbose("JsKit", "Stop message for app not running...");
    }

    public WebviewClientPack getWebappInfoByUuid(String uuidString) {
        try {
            return getWebappInfoByUuid(UUID.fromString(uuidString));
        } catch (Exception e) {
            Trace.debug("JsKit", "getWebappInfoByUuid: ", e);
            return null;
        }
    }

    public WebviewClientPack getWebappInfoByUuid(UUID uuid) {
        if (uuid == null) {
            Trace.debug("JsKit", "getWebappInfoByUuid: uuid is null");
            return null;
        }
        WebviewClientPack rv = getStandardWebappInfoByUuid(uuid);
        if (rv != null) {
            return rv;
        }
        Trace.debug("JsKit", "getWebappInfoByUuid: rv is null");
        return getBuiltinWebappInfoByUuid(uuid);
    }

    public WebviewClientPack getStandardWebappInfoByUuid(UUID uuid) {
        if (uuid == null) {
            Trace.debug("JsKit", "getWebappInfoByUuid: uuid is null");
            return null;
        }
        synchronized (this.mWebviewClients) {
            for (Entry<UUID, WebviewClientPack> ent : this.mWebviewClients.entrySet()) {
                try {
                    WebviewClientPack webviewClientPack;
                    if (((UUID) ent.getKey()).equals(uuid)) {
                        webviewClientPack = (WebviewClientPack) ent.getValue();
                        return webviewClientPack;
                    } else if (uuid.equals(((WebviewClientPack) ent.getValue()).currentActiveAppUuid())) {
                        webviewClientPack = (WebviewClientPack) ent.getValue();
                        return webviewClientPack;
                    }
                } catch (Exception e) {
                    Trace.debug("JsKit", "getStandardWebappInfoByUuid", e);
                }
            }
            return null;
        }
    }

    public WebviewClientPack getBuiltinWebappInfoByUuid(UUID uuid) {
        if (uuid == null) {
            return null;
        }
        synchronized (this.mBuiltinWebviewClients) {
            for (Entry<String, WebviewClientPack> ent : this.mBuiltinWebviewClients.entrySet()) {
                try {
                    WebappRunHost ref;
                    WebviewClientPack v = (WebviewClientPack) ent.getValue();
                    if (v.mWebviewClient != null) {
                        ref = (WebappRunHost) v.mWebviewClient.get();
                    } else {
                        ref = null;
                    }
                    if (ref != null && uuid.equals(ref.clientUuid())) {
                        return v;
                    }
                } catch (Exception e) {
                    Trace.debug("JsKit", "getBuiltinWebappInfoByUuid", e);
                }
            }
            return null;
        }
    }

    public WebviewClientPack queryAnotherJsAppRunning(UUID filterOutJsAppUuid) {
        return queryAnotherJsAppRunning(filterOutJsAppUuid, false);
    }

    public WebviewClientPack queryAnotherJsAppRunning(UUID filterOutJsAppUuid, boolean includeBuiltins) {
        List<UUID> runningList = jsKitAccess().currentlyRunningJsApplications(true, includeBuiltins);
        if (runningList == null) {
            Trace.debug("JsKit", "queryAnotherJsAppRunning: runningList is null");
            return null;
        }
        runningList.remove(filterOutJsAppUuid);
        if (runningList.size() > 0) {
            return jsKitAccess().getWebappInfoByUuid((UUID) runningList.get(0));
        }
        return null;
    }

    public Set<UUID> getAllSpawnedClientsByGivenClientUuid(String uuidString) {
        try {
            return getAllSpawnedClientsByGivenClientUuid(UUID.fromString(uuidString));
        } catch (Exception e) {
            Trace.debug("JsKit", "getAllSpawnedClientsByGivenClientUuid", e);
            return null;
        }
    }

    public Set<UUID> getAllSpawnedClientsByGivenClientUuid(UUID uuid) {
        if (uuid == null) {
            Trace.debug("JsKit", "getAllSpawnedClientsByGivenClientUuid: uuid is null");
            return null;
        }
        WebviewClientPack clientPack = getWebappInfoByUuid(uuid);
        if (clientPack != null) {
            return clientPack.getSpawnedClientsSetCopy();
        }
        Trace.debug("JsKit", "getAllSpawnedClientsByGivenClientUuid: clientPack is null");
        return null;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public boolean isKnownJsAppClient(java.util.UUID r11) {
        /*
        r10 = this;
        r7 = 1;
        r6 = 0;
        if (r11 != 0) goto L_0x000d;
    L_0x0004:
        r5 = "JsKit";
        r7 = "isKnownJsAppClient: uuid is null";
        com.getpebble.android.common.core.trace.Trace.debug(r5, r7);
        r5 = r6;
    L_0x000c:
        return r5;
    L_0x000d:
        r8 = r10.mWebviewClients;
        monitor-enter(r8);
        r5 = r10.mWebviewClients;	 Catch:{ all -> 0x0071 }
        r5 = r5.entrySet();	 Catch:{ all -> 0x0071 }
        r2 = r5.iterator();	 Catch:{ all -> 0x0071 }
    L_0x001a:
        r5 = r2.hasNext();	 Catch:{ all -> 0x0071 }
        if (r5 == 0) goto L_0x0035;
    L_0x0020:
        r1 = r2.next();	 Catch:{ all -> 0x0071 }
        r1 = (java.util.Map.Entry) r1;	 Catch:{ all -> 0x0071 }
        r5 = r1.getKey();	 Catch:{ all -> 0x0071 }
        r5 = (java.util.UUID) r5;	 Catch:{ all -> 0x0071 }
        r5 = r5.equals(r11);	 Catch:{ all -> 0x0071 }
        if (r5 == 0) goto L_0x001a;
    L_0x0032:
        monitor-exit(r8);	 Catch:{ all -> 0x0071 }
        r5 = r7;
        goto L_0x000c;
    L_0x0035:
        monitor-exit(r8);	 Catch:{ all -> 0x0071 }
        r8 = r10.mBuiltinWebviewClients;
        monitor-enter(r8);
        r5 = r10.mBuiltinWebviewClients;	 Catch:{ all -> 0x007e }
        r5 = r5.entrySet();	 Catch:{ all -> 0x007e }
        r2 = r5.iterator();	 Catch:{ all -> 0x007e }
    L_0x0043:
        r5 = r2.hasNext();	 Catch:{ all -> 0x007e }
        if (r5 == 0) goto L_0x0081;
    L_0x0049:
        r0 = r2.next();	 Catch:{ all -> 0x007e }
        r0 = (java.util.Map.Entry) r0;	 Catch:{ all -> 0x007e }
        r4 = r0.getValue();	 Catch:{ all -> 0x007e }
        r4 = (com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack) r4;	 Catch:{ all -> 0x007e }
        r5 = r4.mWebviewClient;	 Catch:{ all -> 0x007e }
        if (r5 == 0) goto L_0x0074;
    L_0x0059:
        r5 = r4.mWebviewClient;	 Catch:{ all -> 0x007e }
        r5 = r5.get();	 Catch:{ all -> 0x007e }
        r5 = (com.getpebble.android.jskit.webapps.WebappRunHost) r5;	 Catch:{ all -> 0x007e }
        r3 = r5;
    L_0x0062:
        if (r3 == 0) goto L_0x0076;
    L_0x0064:
        r5 = r3.clientUuid();	 Catch:{ all -> 0x007e }
        r5 = r11.equals(r5);	 Catch:{ all -> 0x007e }
        if (r5 == 0) goto L_0x0043;
    L_0x006e:
        monitor-exit(r8);	 Catch:{ all -> 0x007e }
        r5 = r7;
        goto L_0x000c;
    L_0x0071:
        r5 = move-exception;
        monitor-exit(r8);	 Catch:{ all -> 0x0071 }
        throw r5;
    L_0x0074:
        r3 = 0;
        goto L_0x0062;
    L_0x0076:
        r5 = "JsKit";
        r9 = "isKnownJsAppClient: ref is null";
        com.getpebble.android.common.core.trace.Trace.debug(r5, r9);	 Catch:{ all -> 0x007e }
        goto L_0x0043;
    L_0x007e:
        r5 = move-exception;
        monitor-exit(r8);	 Catch:{ all -> 0x007e }
        throw r5;
    L_0x0081:
        monitor-exit(r8);	 Catch:{ all -> 0x007e }
        r5 = r6;
        goto L_0x000c;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.JsKit.isKnownJsAppClient(java.util.UUID):boolean");
    }

    public Boolean wasJsAppSuccessfulOnReadyCallback(UUID uuid) {
        Boolean bool = null;
        if (uuid == null) {
            Trace.debug("JsKit", "wasJsAppSuccessfulOnReadyCallback: uuid is null");
        } else {
            synchronized (this.mWebviewClients) {
                WebviewClientPack clientPack = getStandardWebappInfoByUuid(uuid);
                if (clientPack != null) {
                    bool = Boolean.valueOf(clientPack.wasSuccessfulOnReadyCallbackExec());
                } else {
                    Trace.debug("JsKit", "wasJsAppSuccessfulOnReadyCallback: mWebviewClients / clientPack is null");
                    synchronized (this.mBuiltinWebviewClients) {
                        clientPack = getBuiltinWebappInfoByUuid(uuid);
                        if (clientPack != null) {
                            bool = Boolean.valueOf(clientPack.wasSuccessfulOnReadyCallbackExec());
                        } else {
                            Trace.debug("JsKit", "wasJsAppSuccessfulOnReadyCallback: mBuiltinWebviewClients / clientPack is null");
                        }
                    }
                }
            }
        }
        return bool;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public void onJsAppReadyCallbackTouch(java.util.UUID r4) {
        /*
        r3 = this;
        if (r4 != 0) goto L_0x000a;
    L_0x0002:
        r1 = "JsKit";
        r2 = "onJsAppReadyCallbackTouch: uuid is null";
        com.getpebble.android.common.core.trace.Trace.debug(r1, r2);
    L_0x0009:
        return;
    L_0x000a:
        r2 = r3.mWebviewClients;
        monitor-enter(r2);
        r0 = r3.getStandardWebappInfoByUuid(r4);	 Catch:{ all -> 0x0018 }
        if (r0 == 0) goto L_0x001b;
    L_0x0013:
        r0.readyCallbackTouch();	 Catch:{ all -> 0x0018 }
        monitor-exit(r2);	 Catch:{ all -> 0x0018 }
        goto L_0x0009;
    L_0x0018:
        r1 = move-exception;
        monitor-exit(r2);	 Catch:{ all -> 0x0018 }
        throw r1;
    L_0x001b:
        monitor-exit(r2);	 Catch:{ all -> 0x0018 }
        r2 = r3.mBuiltinWebviewClients;
        monitor-enter(r2);
        r0 = r3.getBuiltinWebappInfoByUuid(r4);	 Catch:{ all -> 0x002a }
        if (r0 == 0) goto L_0x002d;
    L_0x0025:
        r0.readyCallbackTouch();	 Catch:{ all -> 0x002a }
        monitor-exit(r2);	 Catch:{ all -> 0x002a }
        goto L_0x0009;
    L_0x002a:
        r1 = move-exception;
        monitor-exit(r2);	 Catch:{ all -> 0x002a }
        throw r1;
    L_0x002d:
        monitor-exit(r2);	 Catch:{ all -> 0x002a }
        goto L_0x0009;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.JsKit.onJsAppReadyCallbackTouch(java.util.UUID):void");
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public boolean isKnownCurrentActiveJsApp(java.util.UUID r11) {
        /*
        r10 = this;
        r8 = 1;
        r7 = 0;
        if (r11 != 0) goto L_0x0006;
    L_0x0004:
        r6 = r7;
    L_0x0005:
        return r6;
    L_0x0006:
        r9 = r10.mWebviewClients;
        monitor-enter(r9);
        r6 = r10.mWebviewClients;	 Catch:{ all -> 0x006e }
        r6 = r6.entrySet();	 Catch:{ all -> 0x006e }
        r3 = r6.iterator();	 Catch:{ all -> 0x006e }
    L_0x0013:
        r6 = r3.hasNext();	 Catch:{ all -> 0x006e }
        if (r6 == 0) goto L_0x0032;
    L_0x0019:
        r2 = r3.next();	 Catch:{ all -> 0x006e }
        r2 = (java.util.Map.Entry) r2;	 Catch:{ all -> 0x006e }
        r6 = r2.getValue();	 Catch:{ all -> 0x006e }
        r6 = (com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack) r6;	 Catch:{ all -> 0x006e }
        r0 = r6.currentActiveAppUuid();	 Catch:{ all -> 0x006e }
        r6 = r11.equals(r0);	 Catch:{ all -> 0x006e }
        if (r6 == 0) goto L_0x0013;
    L_0x002f:
        monitor-exit(r9);	 Catch:{ all -> 0x006e }
        r6 = r8;
        goto L_0x0005;
    L_0x0032:
        monitor-exit(r9);	 Catch:{ all -> 0x006e }
        r9 = r10.mBuiltinWebviewClients;
        monitor-enter(r9);
        r6 = r10.mBuiltinWebviewClients;	 Catch:{ all -> 0x0076 }
        r6 = r6.entrySet();	 Catch:{ all -> 0x0076 }
        r3 = r6.iterator();	 Catch:{ all -> 0x0076 }
    L_0x0040:
        r6 = r3.hasNext();	 Catch:{ all -> 0x0076 }
        if (r6 == 0) goto L_0x0073;
    L_0x0046:
        r1 = r3.next();	 Catch:{ all -> 0x0076 }
        r1 = (java.util.Map.Entry) r1;	 Catch:{ all -> 0x0076 }
        r5 = r1.getValue();	 Catch:{ all -> 0x0076 }
        r5 = (com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack) r5;	 Catch:{ all -> 0x0076 }
        r6 = r5.mWebviewClient;	 Catch:{ all -> 0x0076 }
        if (r6 == 0) goto L_0x0071;
    L_0x0056:
        r6 = r5.mWebviewClient;	 Catch:{ all -> 0x0076 }
        r6 = r6.get();	 Catch:{ all -> 0x0076 }
        r6 = (com.getpebble.android.jskit.webapps.WebappRunHost) r6;	 Catch:{ all -> 0x0076 }
        r4 = r6;
    L_0x005f:
        if (r4 == 0) goto L_0x0040;
    L_0x0061:
        r6 = r4.clientUuid();	 Catch:{ all -> 0x0076 }
        r6 = r11.equals(r6);	 Catch:{ all -> 0x0076 }
        if (r6 == 0) goto L_0x0040;
    L_0x006b:
        monitor-exit(r9);	 Catch:{ all -> 0x0076 }
        r6 = r8;
        goto L_0x0005;
    L_0x006e:
        r6 = move-exception;
        monitor-exit(r9);	 Catch:{ all -> 0x006e }
        throw r6;
    L_0x0071:
        r4 = 0;
        goto L_0x005f;
    L_0x0073:
        monitor-exit(r9);	 Catch:{ all -> 0x0076 }
        r6 = r7;
        goto L_0x0005;
    L_0x0076:
        r6 = move-exception;
        monitor-exit(r9);	 Catch:{ all -> 0x0076 }
        throw r6;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.JsKit.isKnownCurrentActiveJsApp(java.util.UUID):boolean");
    }

    public void changeSelfWebappProcessState(String clientCallerId, WebappProcessState newState) {
        changeWebappProcessStateByUuid(clientCallerId == null ? new UUID(0, 0) : UUID.fromString(clientCallerId), newState);
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public void changeWebappProcessStateByUuid(java.util.UUID r6, com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack.WebappProcessState r7) {
        /*
        r5 = this;
        r0 = r5.getWebappInfoByUuid(r6);
        if (r0 != 0) goto L_0x0007;
    L_0x0006:
        return;
    L_0x0007:
        r3 = r5.mWebappProcessTable;
        monitor-enter(r3);
        r1 = r0.getClientJsProcessId();	 Catch:{ all -> 0x0012 }
        if (r1 != 0) goto L_0x0015;
    L_0x0010:
        monitor-exit(r3);	 Catch:{ all -> 0x0012 }
        goto L_0x0006;
    L_0x0012:
        r2 = move-exception;
        monitor-exit(r3);	 Catch:{ all -> 0x0012 }
        throw r2;
    L_0x0015:
        r2 = r5.mWebappProcessTable;	 Catch:{ all -> 0x0012 }
        r2 = r2.containsKey(r1);	 Catch:{ all -> 0x0012 }
        if (r2 == 0) goto L_0x0021;
    L_0x001d:
        r0.mProcessState = r7;	 Catch:{ all -> 0x0012 }
    L_0x001f:
        monitor-exit(r3);	 Catch:{ all -> 0x0012 }
        goto L_0x0006;
    L_0x0021:
        r2 = r5.mWebappProcessTable;	 Catch:{ all -> 0x0012 }
        r4 = new java.lang.ref.WeakReference;	 Catch:{ all -> 0x0012 }
        r4.<init>(r0);	 Catch:{ all -> 0x0012 }
        r2.put(r1, r4);	 Catch:{ all -> 0x0012 }
        goto L_0x001f;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.JsKit.changeWebappProcessStateByUuid(java.util.UUID, com.getpebble.android.jskit.webapps.JsKit$WebviewClientPack$WebappProcessState):void");
    }

    public void signalWebappRunHostOnDestroy(String clientCallerId, boolean isOnDestroyTheFullTeardown) {
        if (isOnDestroyTheFullTeardown) {
            fullWebappTeardown(clientCallerId);
        }
    }

    protected void fullWebappTeardown(String webAppUuidString) {
        try {
            fullWebappTeardown(UUID.fromString(webAppUuidString));
        } catch (Exception e) {
            Trace.debug("JsKit", "fullWebappTeardown", e);
        }
    }

    protected void fullWebappTeardown(UUID webAppUuid) {
        try {
            WebviewClientPack clientPack;
            synchronized (this.mWebviewClients) {
                synchronized (this.mBuiltinWebviewClients) {
                    clientPack = getWebappInfoByUuid(webAppUuid);
                    if (clientPack != null) {
                        WebappRunHost hostRef = (WebappRunHost) clientPack.mWebviewClient.get();
                        if (hostRef != null) {
                            unregisterWebclient(hostRef);
                        }
                    }
                }
            }
            if (clientPack != null) {
                synchronized (this.mWebappProcessTable) {
                    this.mWebappProcessTable.remove(clientPack.getClientJsProcessId());
                }
            }
        } catch (Exception e) {
            Trace.debug("JsKit", "fullWebappTeardown", e);
        }
    }

    public static synchronized JsKit jsKitAccess() {
        JsKit jsKit;
        synchronized (JsKit.class) {
            jsKit = JsKitRef.INST;
        }
        return jsKit;
    }

    protected JsKit() {
        PebbleWebappBaseActivity.LogSimpleDebug("Construction: New JsKit()");
        jsKitInstalledAppsLockAccess().lock();
        this.mInstalledApps = InstalledAppsBridge.getInstance(JsAppContextBridge.getInstance().getAppContext()).scanForInstalledWebApps();
        try {
            for (UUID jsAppUuid : this.mInstalledApps.keySet()) {
                JsAppPersistentSettings.tryLoad(jsAppUuid);
            }
        } catch (Exception e) {
            Trace.debug("JsKit", "JsKit()", e);
        }
        jsKitInstalledAppsLockAccess().unlock();
    }

    public static String webAppInstallDirectoryAbsPath() {
        return JsAppInstaller.getInstance(JsAppContextBridge.getInstance().getAppContext()).getInstallDir().getAbsolutePath();
    }

    public boolean digestMatch(JsInstalledApplicationInfo a, JsInstalledApplicationInfo b) {
        if (a == null || b == null) {
            return false;
        }
        String[] dA = a.digests();
        String[] dB = b.digests();
        if (dA[0].equals(dB[0]) && dA[1].equals(dB[1])) {
            return true;
        }
        return false;
    }

    public void rescanForInstalledWebApps() {
        Map<UUID, JsInstalledApplicationInfo> rescanResults = InstalledAppsBridge.getInstance(JsAppContextBridge.getInstance().getAppContext()).scanForInstalledWebApps();
        int newlyFound = 0;
        jsKitInstalledAppsLockAccess().lock();
        for (Entry<UUID, JsInstalledApplicationInfo> rescanEntry : rescanResults.entrySet()) {
            JsInstalledApplicationInfo existingInstallInfo = (JsInstalledApplicationInfo) this.mInstalledApps.get(rescanEntry.getKey());
            boolean alreadyInstalled = existingInstallInfo != null;
            if (alreadyInstalled) {
                WebviewClientPack clientPack;
                if (digestMatch(existingInstallInfo, (JsInstalledApplicationInfo) rescanEntry.getValue())) {
                    clientPack = jsKitAccess().getWebappInfoByUuid(existingInstallInfo.getUuid());
                } else {
                    clientPack = jsKitAccess().getWebappInfoByUuid(existingInstallInfo.getUuid());
                }
                if (clientPack != null) {
                    clientPack.clearWebviewCache();
                    PebbleWebappBaseActivity.closeWebapp(jsKitAccess().getWebappBaseActivityTempRef(), clientPack.clientUuid().toString(), WebappTypeE.NoUi);
                }
            }
            this.mInstalledApps.put(rescanEntry.getKey(), rescanEntry.getValue());
            try {
                JsAppPersistentSettings.tryLoad((UUID) rescanEntry.getKey());
            } catch (Exception e) {
                Trace.debug("JsKit", "rescanForInstalledWebApps", e);
            }
            newlyFound++;
            if (!alreadyInstalled) {
                synchronized (this.mDelayedLaunchParamsMap) {
                    this.mDelayedLaunchParamsMap.put(rescanEntry.getKey(), new DelayedLaunchParams(true));
                }
            }
        }
        jsKitInstalledAppsLockAccess().unlock();
    }

    public static void signalJsAppDirectoryRemoved(String appDirAbsPath) {
        if (appDirAbsPath != null) {
            try {
                String s = new File(appDirAbsPath).getCanonicalFile().getAbsolutePath();
                if (s != null) {
                    appDirAbsPath = s;
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "signalJsAppDirectoryRemoved", e);
            }
            jsKitInstalledAppsLockAccess().lock();
            ArrayList<UUID> removeList = new ArrayList();
            for (Entry<UUID, JsInstalledApplicationInfo> e2 : jsKitAccess().mInstalledApps.entrySet()) {
                JsInstalledApplicationInfo appInfoObject = (JsInstalledApplicationInfo) e2.getValue();
                if (appInfoObject != null && appDirAbsPath.equals(appInfoObject.getInstalledAbsPathOnFilesystem())) {
                    removeList.add(appInfoObject.getUuid());
                }
            }
            Iterator i$ = removeList.iterator();
            while (i$.hasNext()) {
                jsKitAccess().mInstalledApps.remove((UUID) i$.next());
            }
            jsKitInstalledAppsLockAccess().unlock();
        }
    }

    public static JsInstalledApplicationInfo installedWebappsInfoForUuid(UUID appUuid) {
        if (appUuid == null) {
            return null;
        }
        if (appUuid.equals(JsKitConstants.InvalidUuid())) {
            return JsInstalledApplicationInfo.makeNativeAppPlaceholderObject();
        }
        jsKitInstalledAppsLockAccess().lock();
        JsInstalledApplicationInfo rv = (JsInstalledApplicationInfo) jsKitAccess().mInstalledApps.get(appUuid);
        jsKitInstalledAppsLockAccess().unlock();
        return rv == null ? JsInstalledApplicationInfo.makeNativeAppPlaceholderObject() : rv;
    }

    public static boolean queryLaunchOnMessageAllowed(UUID jsAppUuid) {
        if (jsAppUuid == null) {
            return false;
        }
        LaunchOnMessageSettingE launchSetting = JsAppPersistentSettings.queryAppLaunchOnMessage(jsAppUuid);
        if (launchSetting.equals(LaunchOnMessageSettingE._INVALID_) || launchSetting.equals(LaunchOnMessageSettingE.NotDeclared)) {
            launchSetting = JsAppPersistentSettings.querySystemGlobalLaunchOnMessage();
        }
        if (launchSetting.equals(LaunchOnMessageSettingE.Yes)) {
            return true;
        }
        return false;
    }

    public static boolean isBuiltInTypeByStaticDeterminants(WebappRunHost client) {
        return false;
    }

    public void registerWebclient(WebappRunHost client) {
        WebviewClientPack obj;
        Throwable th;
        WebviewClientPack webviewClientPack;
        if (client != null) {
            if (isBuiltInTypeByStaticDeterminants(client)) {
                String builtInClassName = client.getClass().getCanonicalName();
                synchronized (this.mBuiltinWebviewClients) {
                    try {
                        List<String> removeList = new ArrayList();
                        boolean alreadyExists = false;
                        for (Entry<String, WebviewClientPack> entry : this.mBuiltinWebviewClients.entrySet()) {
                            if (((WebviewClientPack) entry.getValue()).mWebviewClient == null) {
                                removeList.add(entry.getKey());
                            } else if (((WebviewClientPack) entry.getValue()).mWebviewClient.get() == null) {
                                removeList.add(entry.getKey());
                            } else if (((String) entry.getKey()).equals(builtInClassName)) {
                                alreadyExists = true;
                            }
                        }
                        for (String key : removeList) {
                            this.mBuiltinWebviewClients.remove(key);
                        }
                        if (alreadyExists) {
                            return;
                        }
                        obj = new WebviewClientPack(client);
                        try {
                            obj.setAsBuiltIn().setAsImmortal();
                            this.mBuiltinWebviewClients.put(builtInClassName, obj);
                        } catch (Throwable th2) {
                            th = th2;
                            webviewClientPack = obj;
                            throw th;
                        }
                    } catch (Throwable th3) {
                        th = th3;
                    }
                }
            } else {
                synchronized (this.mWebviewClients) {
                    try {
                        WebviewClientPack tst = (WebviewClientPack) this.mWebviewClients.get(client.clientUuid());
                        if (tst != null) {
                            if (tst.mWebviewClient.get() != null) {
                                return;
                            }
                            this.mWebviewClients.remove(client.clientUuid());
                        }
                        obj = new WebviewClientPack(client);
                        try {
                            this.mWebviewClients.put(client.clientUuid(), obj);
                        } catch (Throwable th4) {
                            th = th4;
                            webviewClientPack = obj;
                            throw th;
                        }
                    } catch (Throwable th5) {
                        th = th5;
                        throw th;
                    }
                }
            }
        }
    }

    public void unregisterWebclient(WebappRunHost client) {
        if (client != null) {
            if (isBuiltInTypeByStaticDeterminants(client)) {
                String builtInClassName = client.getClass().getCanonicalName();
                synchronized (this.mBuiltinWebviewClients) {
                    this.mBuiltinWebviewClients.remove(builtInClassName);
                }
                return;
            }
            synchronized (this.mWebviewClients) {
                this.mWebviewClients.remove(client.clientUuid());
            }
        }
    }

    public WebappRunHost getClientTempRef(String clientCallerId) {
        return getClientTempRef(clientCallerId == null ? new UUID(0, 0) : UUID.fromString(clientCallerId));
    }

    protected WebappRunHost getClientTempRef(UUID clientCallerId) {
        WebviewClientPack clientPack = getWebappInfoByUuid(clientCallerId);
        if (clientPack != null) {
            return clientPack.getTempRef();
        }
        return null;
    }

    public PebbleBabel getMessageTranslatorForClient(String clientCallerIdString) {
        UUID clientCallerId = null;
        try {
            clientCallerId = UUID.fromString(clientCallerIdString);
        } catch (Exception e) {
            Trace.debug("JsKit", "getMessageTranslatorForClient", e);
        }
        return getMessageTranslatorForClient(clientCallerId);
    }

    public PebbleBabel getMessageTranslatorForClient(UUID clientCallerId) {
        UUID key;
        if (clientCallerId == null) {
            key = new UUID(0, 0);
        } else {
            key = clientCallerId;
        }
        WebviewClientPack clientPack = getWebappInfoByUuid(key);
        if (clientPack != null) {
            return clientPack.mMessageTranslatorForThisClient;
        }
        return null;
    }

    public Object[] getClient(String clientCallerId) {
        return getClient(clientCallerId == null ? new UUID(0, 0) : UUID.fromString(clientCallerId));
    }

    protected Object[] getClient(UUID clientCallerId) {
        WebappRunHost webappRunHost = null;
        WebviewClientPack clientPack = getWebappInfoByUuid(clientCallerId);
        if (clientPack != null) {
            Object[] objArr = new Object[2];
            if (clientPack.mWebviewClient != null) {
                webappRunHost = (WebappRunHost) clientPack.mWebviewClient.get();
            }
            objArr[0] = webappRunHost;
            objArr[1] = clientPack.mMessageTranslatorForThisClient;
            return objArr;
        }
        return new Object[]{null, null};
    }

    public UUID currentActiveAppUuid(String clientCallerIdString) {
        synchronized (this.mWebviewClients) {
            PebbleBabel tran = getMessageTranslatorForClient(clientCallerIdString);
            if (tran != null) {
                UUID currentActiveAppUuid = tran.currentActiveAppUuid();
                return currentActiveAppUuid;
            }
            return null;
        }
    }

    public UUID currentActiveAppUuid(UUID clientCallerId) {
        synchronized (this.mWebviewClients) {
            PebbleBabel tran = getMessageTranslatorForClient(clientCallerId);
            if (tran != null) {
                UUID currentActiveAppUuid = tran.currentActiveAppUuid();
                return currentActiveAppUuid;
            }
            return null;
        }
    }

    public UUID reverseCurrentActiveAppUuid(UUID currentActiveAppUuid) {
        UUID uuid = null;
        if (currentActiveAppUuid != null) {
            synchronized (this.mWebviewClients) {
                for (Entry<UUID, WebviewClientPack> entry : this.mWebviewClients.entrySet()) {
                    WebviewClientPack clientPack = (WebviewClientPack) entry.getValue();
                    if (clientPack != null && currentActiveAppUuid.equals(clientPack.currentActiveAppUuid())) {
                        uuid = (UUID) entry.getKey();
                        break;
                    }
                }
            }
        }
        return uuid;
    }

    public UUID reverseAttachedAppUuid(UUID previouslyAttachedToClientPackAppUuid) {
        UUID uuid = null;
        if (previouslyAttachedToClientPackAppUuid != null) {
            synchronized (this.mWebviewClients) {
                for (Entry<UUID, WebviewClientPack> entry : this.mWebviewClients.entrySet()) {
                    WebviewClientPack clientPack = (WebviewClientPack) entry.getValue();
                    if (clientPack != null && clientPack.isWebappUuidOneOfAttached(previouslyAttachedToClientPackAppUuid)) {
                        uuid = (UUID) entry.getKey();
                        break;
                    }
                }
            }
        }
        return uuid;
    }

    public void registerJavascriptAppinfo(String callerIdString, String appInfoJsonString, String newRegisteredJsAppUuidString) {
        WebviewClientPack clientPack = jsKitAccess().getWebappInfoByUuid(callerIdString);
        if (clientPack != null) {
            clientPack.setAttachedWebappUuidStringViaRegisterWebappCall(newRegisteredJsAppUuidString);
        }
    }

    public void startupScriptHasLoaded(String callerIdString, String url, boolean callerSpecificLoadingSucceeded) {
    }

    public void signalAppScriptLoadedByBootstrap(String callerIdString, boolean externalRegisterWebappNeeded, String newRegisteredJsAppUuidString) {
        UUID uuid = null;
        try {
            uuid = UUID.fromString(newRegisteredJsAppUuidString);
            resendAllQueuedAppMessageReceivedEvents(uuid);
        } catch (Exception e) {
            Trace.debug("JsKit", "signalAppScriptLoadedByBootstrap", e);
        }
        synchronized (this.mDelayedLaunchParamsMap) {
            try {
                DelayedLaunchParams params = (DelayedLaunchParams) this.mDelayedLaunchParamsMap.get(uuid);
                if (params != null) {
                    this.mDelayedLaunchParamsMap.remove(uuid);
                    if (params.ShowConfig) {
                        WebviewClientPack clientPack = jsKitAccess().getWebappInfoByUuid(uuid);
                        if (clientPack != null) {
                            WebappRunHost hostClientObject;
                            if (clientPack.mWebviewClient == null) {
                                hostClientObject = null;
                            } else {
                                hostClientObject = (WebappRunHost) clientPack.mWebviewClient.get();
                            }
                            if (hostClientObject != null && clientPack.getSpawnedClientsSetCopy().isEmpty()) {
                                jsKitAccess().signalOneWebappWebUiBringupOpportunity(WebUiBringUpOpportunityTypeE.settings, hostClientObject);
                            }
                        }
                    }
                }
            } catch (Exception e2) {
                Trace.debug("JsKit", "signalAppScriptLoadedByBootstrap", e2);
            }
        }
    }

    public void showToast(String toast) {
        Toast.makeText(JsAppContextBridge.getInstance().getAppContext(), toast, 0).show();
    }

    public void executeHttp(String tag) {
        TransactionManagement.transactionManagement().executeTransaction(tag);
    }

    public String httpGetInitiate(String callerIdString, String url, String jsonObjectStringCustomAddedHeaders, String replyTag) {
        return TransactionManagement.transactionManagement().httpGet(getClientTempRef(callerIdString), url);
    }

    public String httpPostInitiateKeyValueData(String callerIdString, String url, String jsonObjectStringCustomAddedHeaders, String jsonObjectStringDataKVPairs, String replyTag) {
        return "";
    }

    public String httpPostInitiateBodyAsData(String callerIdString, String url, String jsonObjectStringCustomAddedHeaders, String bodyData, String replyTag) {
        return "";
    }

    public void showSimpleNotificationOnPebble(String title, String notificationText) {
        DeviceBridge bridge = DeviceBridge.getInstance();
        if (bridge.isConnected()) {
            bridge.postSimpleNotification(title, notificationText, SimpleDateFormat.getDateTimeInstance().format(new Date()));
        }
    }

    public void showNotificationOnPebble(String jsonObjectStringNotificationData) {
    }

    public void sendWhichWatchAppIsRunningQueryMessage(String callerIdString) {
        if (DeviceBridge.getInstance().isConnected()) {
            DeviceBridge.getInstance().postQueryRunningApps();
        }
    }

    public void sendStartWatchAppMessage(String callerIdString) {
        sendStartWatchAppMessage(callerIdString, null);
    }

    public void sendStartWatchAppMessage(String callerIdString, String deliberatelyOverriddenWatchAppUuidString) {
        if (DeviceBridge.getInstance().isConnected()) {
            PebbleBabel translator;
            Object[] callerInfo = getClient(callerIdString);
            WebappGenericBaseFragment caller;
            if (callerInfo[0] instanceof WebappGenericBaseFragment) {
                caller = (WebappGenericBaseFragment) callerInfo[0];
            } else {
                caller = null;
            }
            if (callerInfo[1] instanceof PebbleBabel) {
                translator = (PebbleBabel) callerInfo[1];
            } else {
                translator = null;
            }
            if (translator != null) {
                String appUuidString;
                if (deliberatelyOverriddenWatchAppUuidString == null) {
                    appUuidString = translator.currentActiveAppUuid().toString();
                } else {
                    appUuidString = deliberatelyOverriddenWatchAppUuidString;
                }
                UUID appUuid = null;
                try {
                    appUuid = UUID.fromString(appUuidString);
                } catch (Exception e) {
                    Trace.debug("JsKit", "sendStartWatchAppMessage", e);
                }
                if (appUuid != null) {
                    DeviceBridge.getInstance().postStartAppWithUUID(appUuid);
                }
            }
        }
    }

    protected JsInstalledApplicationInfo startWatchAppFromJsKitInternals(UUID uuidOfAppToStart, boolean configLaunchOnStart) {
        if (uuidOfAppToStart == null) {
            Trace.verbose("JsKit", "startWatchAppFromJsKitInternals: uuidOfAppToStart is null");
            return null;
        }
        JsInstalledApplicationInfo appInfo = installedWebappsInfoForUuid(uuidOfAppToStart);
        if (appInfo == null) {
            Trace.verbose("JsKit", "startWatchAppFromJsKitInternals: appInfo is null");
            return null;
        } else if (appInfo.isNativeAppSpecialInfoObject()) {
            Trace.verbose("JsKit", "startWatchAppFromJsKitInternals: appInfo.isNativeAppSpecialInfoObject, not starting");
            return null;
        } else {
            if (configLaunchOnStart) {
                synchronized (this.mDelayedLaunchParamsMap) {
                    this.mDelayedLaunchParamsMap.put(uuidOfAppToStart, new DelayedLaunchParams(true));
                }
            }
            DeviceBridge.getInstance().postStartAppWithUUID(uuidOfAppToStart);
            return appInfo;
        }
    }

    public String sendAppMessage(String callerIdString, String appUuidString, String jsonObjectString) {
        Trace.verbose("JsKit", "sendAppMessage");
        DeviceBridge bridge = DeviceBridge.getInstance();
        if (!bridge.isConnected()) {
            return null;
        }
        Object[] callerInfo = getClient(callerIdString);
        if (callerInfo[0] instanceof WebappGenericBaseFragment) {
            WebappGenericBaseFragment caller = (WebappGenericBaseFragment) callerInfo[0];
        }
        PebbleBabel translator = callerInfo[1] instanceof PebbleBabel ? (PebbleBabel) callerInfo[1] : null;
        if (translator == null) {
            Trace.warning("JsKit", "translator is null");
            return null;
        }
        if (appUuidString == null) {
            appUuidString = translator.currentActiveAppUuid().toString();
        }
        UUID appUuid = null;
        try {
            appUuid = UUID.fromString(appUuidString);
        } catch (Exception e) {
            Trace.debug("JsKit", "error getting UUID", e);
        }
        if (appUuid == null) {
            Trace.warning("JsKit", "appUuid is null");
            return null;
        }
        AppMessage m = translator.translateToAppMessage(appUuidString, jsonObjectString);
        if (m != null) {
            int transactionId = m.getTransactionId() & 255;
            jsKitAccess().appMessageTIDTrackerInstance.sentMessage(appUuidString, m.getTransactionId());
            if (bridge.postAppMessage(m)) {
                return "" + transactionId;
            }
        }
        Trace.warning("JsKit", "m is null");
        return null;
    }

    protected static String makeExtensionsPreparedDataString() {
        try {
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("android");
            jsonArray.put("native_http_get");
            jsonArray.put("native_http_post");
            jsonArray.put("native_settings_storage");
            return jsonArray.toString();
        } catch (Exception e) {
            Trace.debug("JsKit", "makeExtensionsPreparedDataString", e);
            return "{}";
        }
    }

    public String getExtensions() {
        return ExtensionsPreparedDataString;
    }

    public int getVersionCode() {
        return 1;
    }

    public String getAccountToken(String callerId) {
        return generateToken(callerId, TokenBridge.getInstance(JsAppContextBridge.getInstance().getAppContext()).getAccountId());
    }

    public String getWatchToken(String callerId) {
        PblDeviceRecord connectedDeviceRecord = PebbleApplication.getConnectedDeviceRecord();
        if (connectedDeviceRecord == null) {
            Trace.debug("JsKit", "Connected Device Record was null");
            connectedDeviceRecord = PebbleApplication.getLastConnectedDeviceRecord();
            if (connectedDeviceRecord == null) {
                Trace.debug("JsKit", "Last Connected Device Record was null: Returning blank string.");
                return "";
            }
        }
        return generateToken(callerId, connectedDeviceRecord.serialNumber);
    }

    private String generateToken(String callerId, String seed) {
        UUID appUUID = currentActiveAppUuid(callerId);
        if (appUUID == null) {
            return "";
        }
        Context context = JsAppContextBridge.getInstance().getAppContext();
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(seed);
        String developerId = InstalledAppsBridge.getInstance(context).getDeveloperIdForApp(appUUID);
        if (developerId == null) {
            developerId = appUUID.toString().toUpperCase();
        }
        strBuilder.append(developerId);
        strBuilder.append("MMIxeUT[G9/U#(7V67O^EuADSw,{$C;B}`>|-nlrQCs|t|k=P_!*LETm,RKc,BG*'");
        String unhashedToken = strBuilder.toString();
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(unhashedToken.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (byte b : messageDigest) {
                hexString.append(Integer.toHexString(b & 255));
            }
            return hexString.toString();
        } catch (Throwable e) {
            Trace.debug("JsKit", e);
            return "";
        }
    }

    protected void startLaunchTimerForUuid(final UUID webappUuid) {
        if (webappUuid == null) {
            Trace.debug("JsKit", "startLaunchTimerForUuid: webappUuid is null");
            return;
        }
        Trace.debug("JsKit", "Scheduling timeout for " + webappUuid);
        this.mTimeoutHandler.postDelayed(new Runnable() {
            public void run() {
                Trace.debug("JsKit", "Timeout runnable firing for " + webappUuid);
                Boolean result = JsKit.jsKitAccess().wasJsAppSuccessfulOnReadyCallback(webappUuid);
                if (result == null ? false : result.booleanValue()) {
                    Trace.debug("JsKit", "(No timeout for " + webappUuid + ")");
                    return;
                }
                UUID runHostUuid = JsKit.jsKitAccess().reverseAttachedAppUuid(webappUuid);
                JsKit.loggerForWebappsExtended(webappUuid, runHostUuid, "++_JS_LIFECYCLE_++:LAUNCH-FAIL:READY-TIMEOUT");
                PebbleWebappBaseActivity.closeWebapp(JsKit.jsKitAccess().getWebappBaseActivityTempRef(), runHostUuid, WebappTypeE.NoUi);
            }
        }, 8000);
    }

    public boolean launchInstanceOf(UUID jsAppUuid, boolean quietLaunch) {
        if (jsAppUuid != null) {
            return launchInstanceOf(installedWebappsInfoForUuid(jsAppUuid));
        }
        Trace.info("JsKit", "launchInstanceOf: jsAppUuid is null");
        return false;
    }

    public boolean launchInstanceOf(JsInstalledApplicationInfo appInfo) {
        return launchInstanceOf(appInfo, false);
    }

    public boolean launchInstanceOf(JsInstalledApplicationInfo appInfo, boolean quietLaunch) {
        if (appInfo == null) {
            Trace.info("JsKit", "launchInstanceOf: appInfo is null");
            return false;
        }
        UUID effectiveAppUuid;
        if (!(this.mLastRunningMessageUuid == null || this.mLastRunningMessageUuid.equals(appInfo.getUuid()))) {
            Trace.info("JsKit", "Unexpected launch message - previous app (" + this.mLastRunningMessageUuid + ") was not stopped. Killing now before starting new app...");
            onWatchAppStoppedSequenced(this.mLastRunningMessageUuid);
        }
        this.mLastRunningMessageUuid = appInfo.getUuid();
        Trace.debug("JsKit", "Purging timeout handler");
        this.mTimeoutHandler.removeCallbacksAndMessages(null);
        if (appInfo.isNativeAppSpecialInfoObject()) {
            effectiveAppUuid = JsKitConstants.InvalidUuid();
            Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a SPECIAL CASE; This is a Native app on the watch. No launch action here.");
        } else {
            effectiveAppUuid = appInfo.getUuid();
        }
        if (JsAppPersistentSettings.queryAppEnabled(effectiveAppUuid)) {
            try {
                String prependShimRoot = appInfo.getInstalledAbsPathOnFilesystem().startsWith("/") ? "" : "/";
                String launchUrl = "file://" + prependShimRoot + appInfo.getInstalledAbsPathOnFilesystem() + "/pebble-js-app.js";
                String appInfoJsonUrl = "file://" + prependShimRoot + appInfo.getInstalledAbsPathOnFilesystem() + "/appinfo.json";
                WebviewClientPack clientPack = getWebappInfoByUuid(effectiveAppUuid);
                if (clientPack != null) {
                    Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a " + "NO-Go. An instance is already registered");
                    loggerForWebappsExtended(effectiveAppUuid, null, "++_JS_LIFECYCLE_++:PREVIOUSLY-RUNNING");
                    return false;
                }
                if (prvLaunchInstanceOfHelperToCloseRunningJsApp(appInfo, clientPack)) {
                    Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a " + "Go!");
                    loggerForWebappsExtended(appInfo.getUuid(), null, "++_JS_LIFECYCLE_++:LAUNCHING");
                    startLaunchTimerForUuid(appInfo.getUuid());
                    loadUrlIntoNoUiBlankApp("", launchUrl, appInfoJsonUrl, getAvailableActivityRef(), true, quietLaunch);
                    RemoteAppBehavior.logJsAppStarted(appInfo.getUuidString());
                } else {
                    Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a NO-Go.");
                }
                return true;
            } catch (Exception e) {
                Trace.error("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] failed");
                loggerForWebappsExtended(appInfo.getUuid(), null, "++_JS_LIFECYCLE_++:LAUNCH-ABORT:UNKNOWN-FAIL");
                return false;
            }
        }
        Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a " + "NO-Go. app is disabled");
        loggerForWebappsExtended(effectiveAppUuid, null, "++_JS_LIFECYCLE_++:LAUNCH-ABORT:DISABLED");
        return false;
    }

    protected boolean prvLaunchInstanceOfHelperToCloseRunningJsApp(JsInstalledApplicationInfo appInfo, WebviewClientPack clientPack) {
        clientPack = queryAnotherJsAppRunning(appInfo.isNativeAppSpecialInfoObject() ? JsKitConstants.InvalidUuid() : appInfo.getUuid());
        if (clientPack != null) {
            if (clientPack.getSpawnedClientsSetCopy().isEmpty()) {
                Trace.debug("JsKit", "KILLING instance of [ uuid = " + clientPack.currentActiveAppUuid() + "]");
                PebbleWebappBaseActivity.closeWebapp(jsKitAccess().getWebappBaseActivityTempRef(), clientPack.currentActiveAppUuid().toString(), WebappTypeE.NoUi);
            } else {
                Trace.debug("JsKit", "launchInstanceOf() for [" + (appInfo == null ? "(null)" : appInfo.toString()) + "] is a " + "NO-Go. An instance of [ uuid = " + clientPack.currentActiveAppUuid() + "] is already running has a webui spawned");
                loggerForWebappsExtended(appInfo.getUuid(), null, "++_JS_LIFECYCLE_++:LAUNCH-ABORT:OTHER-UI-VISIBLE");
                return false;
            }
        }
        return appInfo.isNormalJsAppObject();
    }

    public void kill(UUID webAppClientUuid, UUID webAppUuid, boolean suppressWatchQueryForRunningApps) {
        fullWebappTeardown(webAppClientUuid);
        loggerForWebappsExtended(webAppUuid, webAppClientUuid, "++_JS_LIFECYCLE_++:KILLED");
        if (!suppressWatchQueryForRunningApps) {
            requestAppRunningUpdateFromWatch(5000);
        }
        Trace.debug("JsKit", "Purging timeout handler");
        this.mTimeoutHandler.removeCallbacksAndMessages(null);
    }

    protected void requestAppRunningUpdateFromWatch(int delay) {
        synchronized (this.mWatchAppRequeryTimer) {
            this.mWatchAppRequeryTimer.schedule(new TimerTask() {
                public void run() {
                    JsKit.jsKitAccess().sendWhichWatchAppIsRunningQueryMessage(null);
                }
            }, (long) delay);
        }
    }

    public String nativeSettingWrite(String callerIdString, String settingName, String settingValue) {
        String str = null;
        if (!(callerIdString == null || settingName == null || settingValue == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
                    if (jsInstalledApplicationInfo != null) {
                        str = JsAppPersistentSettings.writeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName.trim(), settingValue);
                    }
                }
            } catch (Exception e) {
            }
        }
        return str;
    }

    public String nativeSettingWriteWithOptions(String callerIdString, String settingName, String settingValue, String settingValueAndOptsJsonString) {
        if (callerIdString == null || settingName == null || settingValue == null) {
            return null;
        }
        try {
            UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
            if (callerId == null) {
                return null;
            }
            JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
            if (jsInstalledApplicationInfo == null) {
                return null;
            }
            settingName = settingName.trim();
            JSONObject jsonObjectOptions = null;
            try {
                jsonObjectOptions = new JSONObject(settingValueAndOptsJsonString);
            } catch (Exception e) {
                Trace.debug("JsKit", "nativeSettingWriteWithOptions", e);
            }
            if (jsonObjectOptions == null) {
                return JsAppPersistentSettings.writeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName, settingValue);
            }
            boolean alsoWriteAnyVersionSetting = jsonObjectOptions.optBoolean("alsoWriteAnyVersionSetting", false);
            if (jsonObjectOptions.optBoolean("strictlyWriteAnyVersionSetting", false)) {
                return JsAppPersistentSettings.writeAppAnyVersionSetting(callerId, settingName, settingValue);
            }
            if (!alsoWriteAnyVersionSetting) {
                return JsAppPersistentSettings.writeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName, settingValue);
            }
            JsAppPersistentSettings.writeAppAnyVersionSetting(callerId, settingName, settingValue);
            return JsAppPersistentSettings.writeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName, settingValue);
        } catch (Exception e2) {
            Trace.debug("JsKit", "nativeSettingWriteWithOptions", e2);
            return null;
        }
    }

    public String nativeSettingRemove(String callerIdString, String settingName) {
        String str = null;
        if (!(callerIdString == null || settingName == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
                    if (jsInstalledApplicationInfo != null) {
                        str = JsAppPersistentSettings.readAppVersionsSpecificString(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName.trim());
                    }
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "nativeSettingRemove", e);
            }
        }
        return str;
    }

    public String nativeSettingRemoveWithOptions(String callerIdString, String settingName, String settingValueAndOptsJsonString) {
        if (callerIdString == null || settingName == null) {
            return null;
        }
        try {
            UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
            if (callerId == null) {
                return null;
            }
            JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
            if (jsInstalledApplicationInfo == null) {
                return null;
            }
            settingName = settingName.trim();
            JSONObject jsonObjectOptions = null;
            try {
                jsonObjectOptions = new JSONObject(settingValueAndOptsJsonString);
            } catch (Exception e) {
                Trace.debug("JsKit", "nativeSettingRemoveWithOptions", e);
            }
            if (jsonObjectOptions == null) {
                return JsAppPersistentSettings.removeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
            }
            boolean alsoRemoveAnyVersionSetting = jsonObjectOptions.optBoolean("alsoRemoveAnyVersionSetting", false);
            if (jsonObjectOptions.optBoolean("strictlyRemoveAnyVersionSetting", false)) {
                return JsAppPersistentSettings.removeAppAnyVersionSetting(callerId, settingName);
            }
            if (!alsoRemoveAnyVersionSetting) {
                return JsAppPersistentSettings.removeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
            }
            JsAppPersistentSettings.removeAppAnyVersionSetting(callerId, settingName);
            return JsAppPersistentSettings.removeAppVersionSpecificSetting(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
        } catch (Exception e2) {
            Trace.debug("JsKit", "nativeSettingRemoveWithOptions", e2);
            return null;
        }
    }

    public String nativeSettingRead(String callerIdString, String settingName) {
        String str = null;
        if (!(callerIdString == null || settingName == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
                    if (jsInstalledApplicationInfo != null) {
                        str = JsAppPersistentSettings.readAppVersionsSpecificString(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
                    }
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "nativeSettingRead", e);
            }
        }
        return str;
    }

    public String nativeSettingReadWithOptions(String callerIdString, String settingName, String settingValueAndOptsJsonString) {
        if (callerIdString == null || settingName == null) {
            return null;
        }
        try {
            UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
            if (callerId == null) {
                return null;
            }
            JsInstalledApplicationInfo jsInstalledApplicationInfo = installedWebappsInfoForUuid(callerId);
            if (jsInstalledApplicationInfo == null) {
                return null;
            }
            settingName = settingName.trim();
            JSONObject jsonObjectOptions = null;
            try {
                jsonObjectOptions = new JSONObject(settingValueAndOptsJsonString);
            } catch (Exception e) {
                Trace.debug("JsKit", "nativeSettingReadWithOptions", e);
            }
            if (jsonObjectOptions == null) {
                return JsAppPersistentSettings.readAppVersionsSpecificString(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
            }
            if (jsonObjectOptions.optBoolean("strictlyAnyVersionSetting", false)) {
                return JsAppPersistentSettings.readAppAnyVersionSetting(callerId, settingName);
            }
            return JsAppPersistentSettings.readAppVersionsSpecificString(callerId, jsInstalledApplicationInfo.getVersionCode(), settingName);
        } catch (Exception e2) {
            Trace.debug("JsKit", "nativeSettingReadWithOptions", e2);
            return null;
        }
    }

    public String loadUrl(String callerIdString, String restrictedUrl, boolean useBootstrapScripts) {
        return loadUrl(callerIdString, restrictedUrl, null, useBootstrapScripts);
    }

    public String loadUrl(String callerIdString, String restrictedUrl, Activity useThisHostActivity, boolean useBootstrapScripts) {
        WebviewClientPack callerClientPack = jsKitAccess().getWebappInfoByUuid(callerIdString);
        if (callerClientPack == null) {
            return null;
        }
        if (callerClientPack.getSpawnedClientsSetCopy().isEmpty()) {
            PebbleWebappBaseActivity.createNewWebapp(useThisHostActivity, restrictedUrl, callerIdString, useBootstrapScripts);
            return "";
        }
        String str = "%s::%s : caller client object uuid = [%s] already has at least one spawned webapp. Cannot spawn more until existing are closed[%s]";
        Object[] objArr = new Object[3];
        objArr[0] = getClass().getSimpleName();
        objArr[1] = "loadUrl";
        if (callerIdString == null) {
            callerIdString = "(null)";
        }
        objArr[2] = callerIdString;
        PebbleWebappBaseActivity.LogSimpleError(str, objArr);
        return null;
    }

    public String loadUrlIntoNoUiBlankApp(String callerIdString, String restrictedUrl, String appInfoJsonUrl, Activity useThisHostActivity, boolean useBootstrapScripts, boolean quietLaunch) {
        PebbleWebappBaseActivity.createNewNoUiWebapp(useThisHostActivity, restrictedUrl, appInfoJsonUrl, callerIdString, useBootstrapScripts, quietLaunch);
        return "";
    }

    public void clientClose(String callerIdString, String dataLeftBehind, String overrideTag) {
        clientClose(callerIdString, dataLeftBehind, overrideTag, null);
    }

    public void clientClose(String callerIdString, String dataLeftBehind) {
        clientClose(callerIdString, dataLeftBehind, null, null);
    }

    public void clientClose(String callerIdString, String dataLeftBehind, String overrideTag, Activity useThisHostActivity) {
        if (callerIdString != null) {
            setLeaveBehindDataForClient(callerIdString, dataLeftBehind, overrideTag);
            WebviewClientPack clientPack = getWebappInfoByUuid(UUID.fromString(callerIdString));
            UUID linkedCreatedByClientId = null;
            WebappRunHost ref = null;
            WebappTypeE clientType = WebappTypeE.Unknown;
            if (clientPack != null) {
                try {
                    ref = (WebappRunHost) clientPack.mWebviewClient.get();
                    callerIdString = ref.clientUuidAsString();
                } catch (Exception e) {
                    Trace.debug("JsKit", "clientClose", e);
                }
                try {
                    if (ref instanceof WebappGenericBaseFragment) {
                        clientType = WebappTypeE.WebUi;
                        linkedCreatedByClientId = ((WebappGenericBaseFragment) ref).queryCreatedByLinkedClient();
                        Trace.debug("JsKit", linkedCreatedByClientId.toString());
                    } else {
                        clientType = WebappTypeE.NoUi;
                    }
                } catch (Exception e2) {
                    Trace.debug("JsKit", "clientClose", e2);
                }
            }
            commitsendLeaveBehindDataForClient(linkedCreatedByClientId, callerIdString);
            if (clientType.equals(WebappTypeE.Unknown)) {
                clientType = WebappTypeE.NoUi;
            }
            clientPack.setClosing();
            PebbleWebappBaseActivity.closeWebapp(null, callerIdString, clientType);
        }
    }

    public boolean directlyInvokeAppCloseForNoUiApp(WebviewClientPack client) {
        try {
            PebbleWebappBaseActivity.closeWebapp(jsKitAccess().getWebappBaseActivityTempRef(), client.clientUuid().toString(), WebappTypeE.NoUi);
            return true;
        } catch (Exception e) {
            Trace.debug("JsKit", "directlyInvokeAppCloseForNoUiApp", e);
            return false;
        }
    }

    public void setLeaveBehindDataForClient(UUID uuid, String dataToLeave, String optionalTag) {
        try {
            setLeaveBehindDataForClient(uuid.toString(), dataToLeave, optionalTag);
        } catch (Exception e) {
            Trace.debug("JsKit", "setLeaveBehindDataForClient", e);
        }
    }

    public void setLeaveBehindDataForClient(String uuidString, String dataToLeave, String optionalTag) {
        if (uuidString != null) {
            String dataString;
            if (dataToLeave == null) {
                dataString = JsKitConstants.EmptyJsonObjectString();
            } else {
                dataString = dataToLeave;
            }
            JsPseudoIPC.systemInstanceAccess().leaveData(uuidString, optionalTag, dataString);
        }
    }

    public void commitsendLeaveBehindDataForClient(Object uuidOrUuidStringOfTarget, Object uuidOrUuidStringOfSender) {
        UUID target = null;
        String senderUuidStr = null;
        try {
            if (uuidOrUuidStringOfTarget instanceof String) {
                target = UUID.fromString((String) uuidOrUuidStringOfTarget);
            } else if (uuidOrUuidStringOfTarget instanceof UUID) {
                target = (UUID) uuidOrUuidStringOfTarget;
            }
            if (uuidOrUuidStringOfSender instanceof UUID) {
                senderUuidStr = ((UUID) uuidOrUuidStringOfSender).toString();
            } else if (uuidOrUuidStringOfSender instanceof String) {
                senderUuidStr = (String) uuidOrUuidStringOfSender;
            }
        } catch (Exception e) {
            Trace.debug("JsKit", "commitsendLeaveBehindDataForClient", e);
        }
        if (target != null && senderUuidStr != null) {
            JsPIPCDeliveryAgentInstance mailman = new JsPIPCWebappClosedEventDeliveryAgent();
            mailman.setContextTarget(target);
            mailman.setContextData(senderUuidStr);
            JsThreadPools.MainWorkerThreadsExecutorService().execute(new JsPseudoIPCDeliveryTask(mailman));
            mailman.startExecuting();
        }
    }

    public void jsTimerTriggered(String callerIdString, String timerContextData) {
        String str = "JsKit";
        StringBuilder append = new StringBuilder().append("timer: ");
        if (timerContextData == null) {
            timerContextData = "(null)";
        }
        Trace.debug(str, append.append(timerContextData).toString());
    }

    private void queueAppMessageReceivedEventForLaunchPendingApp(UUID jsAppUuid, AppMessageReceivedEvent event) {
        if (jsAppUuid != null && event != null) {
            synchronized (this.mQueuedAppMessageReceivedEvents) {
                List<AppMessageReceivedEvent> queue = (List) this.mQueuedAppMessageReceivedEvents.get(jsAppUuid);
                if (queue == null) {
                    queue = new ArrayList();
                    this.mQueuedAppMessageReceivedEvents.put(jsAppUuid, queue);
                }
                queue.add(event);
            }
        }
    }

    private void resendAllQueuedAppMessageReceivedEvents(UUID jsAppUuid) {
        synchronized (this.mQueuedAppMessageReceivedEvents) {
            List<AppMessageReceivedEvent> queue = (List) this.mQueuedAppMessageReceivedEvents.get(jsAppUuid);
            if (queue == null) {
                return;
            }
            final List<AppMessageReceivedEvent> copyList = new ArrayList();
            for (AppMessageReceivedEvent event : queue) {
                AppMessageReceivedEvent event2 = AppMessageReceivedEvent.copyOf(event2);
                if (event2 != null) {
                    copyList.add(event2);
                }
            }
            clearAllQueuedAppMessageReceivedEvents(jsAppUuid);
            JsThreadPools.MainWorkerThreadsExecutorService().execute(new Runnable() {
                public void run() {
                    for (AppMessageReceivedEvent event : copyList) {
                        JsKit.jsKitAccess().onAppMessageReceivedEvent(event);
                    }
                }
            });
        }
    }

    private void clearAllQueuedAppMessageReceivedEvents(UUID jsAppUuid) {
        if (jsAppUuid != null) {
            synchronized (this.mQueuedAppMessageReceivedEvents) {
                this.mQueuedAppMessageReceivedEvents.remove(jsAppUuid);
            }
        }
    }

    public void onAppMessageReceivedEvent(AppMessageReceivedEvent event) {
        if (event == null) {
            Trace.warning("JsKit", "onAppMessageReceivedEvent: event is null");
            return;
        }
        String str;
        Object[] objArr;
        String str2;
        WebappRunHost ref;
        AppMessage message = event.getMessage();
        UUID clientId = null;
        boolean isAckNack = false;
        SignalMessageTypeE messageTypeE = SignalMessageTypeE.Data;
        if (message.getCommand() == AppMessageCommand.ACK || message.getCommand() == AppMessageCommand.NACK) {
            isAckNack = true;
            messageTypeE = message.getCommand() == AppMessageCommand.ACK ? SignalMessageTypeE.Ack : SignalMessageTypeE.Nack;
            String uuidString = this.appMessageTIDTrackerInstance.ackNackReceived(message.getTransactionId());
            if (uuidString == null) {
                Trace.debug("JsKit", "onAppMessageReceivedEvent: unknown UUID; transaction ID = " + message.getTransactionId());
                return;
            }
            try {
                clientId = UUID.fromString(uuidString);
            } catch (Exception e) {
                Exception e2;
                Trace.warning("JsKit", "onAppMessageReceivedEvent: bad UUID", e2);
            }
            if (clientId == null) {
                Trace.debug("JsKit", "onAppMessageReceivedEvent: client ID is null");
                return;
            }
        }
        clientId = message.getUuid();
        String clientIdString = clientId == null ? null : clientId.toString();
        WebviewClientPack webviewClientPack = null;
        try {
            webviewClientPack = getWebappInfoByUuid(clientId);
            if (webviewClientPack != null) {
                clientId = ((WebappRunHost) webviewClientPack.mWebviewClient.get()).clientUuid();
                clientIdString = clientId == null ? null : clientId.toString();
            } else {
                Trace.warning("JsKit", "onAppMessageReceivedEvent: clientPack is null");
            }
        } catch (Exception e22) {
            Trace.debug("JsKit", "onAppMessageReceivedEvent", e22);
        }
        boolean launchOnMessageAttempted = false;
        if (webviewClientPack == null) {
            str = "%s::%s : cannot retrieve client info for appmessage target Uuid [%s]";
            objArr = new Object[3];
            objArr[0] = getClass().getSimpleName();
            objArr[1] = "onAppMessageReceivedEvent";
            if (clientIdString == null) {
                str2 = "(null)";
            } else {
                str2 = clientIdString;
            }
            objArr[2] = str2;
            PebbleWebappBaseActivity.LogSimpleWarn(str, objArr);
            if (queryLaunchOnMessageAllowed(clientId)) {
                launchOnMessageAttempted = jsKitAccess().launchInstanceOf(clientId, true);
            } else {
                str = "%s::%s : target Uuid [%s] was not running; sending a query to the Pebble device to see if it should be (restarted)";
                objArr = new Object[3];
                objArr[0] = getClass().getSimpleName();
                objArr[1] = "onAppMessageReceivedEvent";
                if (clientIdString == null) {
                    str2 = "(null)";
                } else {
                    str2 = clientIdString;
                }
                objArr[2] = str2;
                PebbleWebappBaseActivity.LogSimpleWarn(str, objArr);
                jsKitAccess().sendWhichWatchAppIsRunningQueryMessage(null);
            }
        }
        JSONObject jsonObject = null;
        if (isAckNack) {
            try {
                JSONObject jsonObject2 = new JSONObject();
                try {
                    jsonObject2.put("transactionId", message.getTransactionId() & 255);
                    jsonObject = jsonObject2;
                } catch (Exception e3) {
                    e22 = e3;
                    jsonObject = jsonObject2;
                    Trace.debug("JsKit", "onAppMessageReceivedEvent", e22);
                    if (jsonObject != null) {
                        try {
                            webviewClientPack = getWebappInfoByUuid(clientId);
                            if (webviewClientPack != null) {
                                if (!isAckNack) {
                                    DeviceBridge.getInstance().postAck(message.getTransactionId());
                                }
                                ref = (WebappRunHost) webviewClientPack.mWebviewClient.get();
                                if (ref == null) {
                                    signalOneWebappOnAppMessageReceived(ref, jsonObject.toString(), messageTypeE);
                                    return;
                                } else if (launchOnMessageAttempted) {
                                    Trace.info("JsKit", "onAppMessageReceivedEvent: queueing AppMessage event for " + clientId);
                                    queueAppMessageReceivedEventForLaunchPendingApp(clientId, event);
                                    return;
                                } else {
                                    Trace.info("JsKit", "onAppMessageReceivedEvent: clearAllQueuedAppMessageReceivedEvents");
                                    clearAllQueuedAppMessageReceivedEvents(clientId);
                                    return;
                                }
                            }
                            Trace.warning("JsKit", "onAppMessageReceivedEvent: clientPack is still null");
                            return;
                        } catch (Exception e222) {
                            Trace.debug("JsKit", "onAppMessageReceivedEvent", e222);
                            return;
                        }
                    }
                    Trace.warning("JsKit", "onAppMessageReceivedEvent: jsonObject is null");
                }
            } catch (Exception e4) {
                e222 = e4;
                Trace.debug("JsKit", "onAppMessageReceivedEvent", e222);
                if (jsonObject != null) {
                    Trace.warning("JsKit", "onAppMessageReceivedEvent: jsonObject is null");
                }
                webviewClientPack = getWebappInfoByUuid(clientId);
                if (webviewClientPack != null) {
                    Trace.warning("JsKit", "onAppMessageReceivedEvent: clientPack is still null");
                    return;
                }
                if (isAckNack) {
                    DeviceBridge.getInstance().postAck(message.getTransactionId());
                }
                ref = (WebappRunHost) webviewClientPack.mWebviewClient.get();
                if (ref == null) {
                    signalOneWebappOnAppMessageReceived(ref, jsonObject.toString(), messageTypeE);
                    return;
                } else if (launchOnMessageAttempted) {
                    Trace.info("JsKit", "onAppMessageReceivedEvent: clearAllQueuedAppMessageReceivedEvents");
                    clearAllQueuedAppMessageReceivedEvents(clientId);
                    return;
                } else {
                    Trace.info("JsKit", "onAppMessageReceivedEvent: queueing AppMessage event for " + clientId);
                    queueAppMessageReceivedEventForLaunchPendingApp(clientId, event);
                    return;
                }
            }
        }
        PebbleBabel translator = getMessageTranslatorForClient(clientIdString);
        if (translator == null) {
            str2 = "%s::%s : no translator found via lookup by client Uuid [%s]";
            Object[] objArr2 = new Object[3];
            objArr2[0] = getClass().getSimpleName();
            objArr2[1] = "onAppMessageReceivedEvent";
            if (clientIdString == null) {
                clientIdString = "(null)";
            }
            objArr2[2] = clientIdString;
            PebbleWebappBaseActivity.LogSimpleError(str2, objArr2);
            return;
        }
        try {
            jsonObject = translator.translateToJsonObject(message);
        } catch (Exception e5) {
            str = "%s::%s ; uuid [%s] : couldn't retrieve data from message parcel and/or translate to jsonobject form";
            objArr = new Object[3];
            objArr[0] = getClass().getSimpleName();
            objArr[1] = "onAppMessageReceivedEvent";
            objArr[2] = clientIdString == null ? "(null)" : clientIdString;
            PebbleWebappBaseActivity.LogSimpleError(str, objArr);
        }
        try {
            str = "%s::%s ; uuid [%s] : RECEIVED: %s";
            objArr = new Object[4];
            objArr[0] = getClass().getSimpleName();
            objArr[1] = "onAppMessageReceivedEvent";
            if (clientIdString == null) {
                clientIdString = "(null)";
            }
            objArr[2] = clientIdString;
            objArr[3] = jsonObject == null ? "(null)" : jsonObject.toString();
            PebbleWebappBaseActivity.LogSimpleInfo(str, objArr);
        } catch (Exception e2222) {
            Trace.debug("JsKit", "onAppMessageReceivedEvent", e2222);
        }
        if (jsonObject != null) {
            webviewClientPack = getWebappInfoByUuid(clientId);
            if (webviewClientPack != null) {
                if (isAckNack) {
                    DeviceBridge.getInstance().postAck(message.getTransactionId());
                }
                ref = (WebappRunHost) webviewClientPack.mWebviewClient.get();
                if (ref == null) {
                    signalOneWebappOnAppMessageReceived(ref, jsonObject.toString(), messageTypeE);
                    return;
                } else if (launchOnMessageAttempted) {
                    Trace.info("JsKit", "onAppMessageReceivedEvent: queueing AppMessage event for " + clientId);
                    queueAppMessageReceivedEventForLaunchPendingApp(clientId, event);
                    return;
                } else {
                    Trace.info("JsKit", "onAppMessageReceivedEvent: clearAllQueuedAppMessageReceivedEvents");
                    clearAllQueuedAppMessageReceivedEvents(clientId);
                    return;
                }
            }
            Trace.warning("JsKit", "onAppMessageReceivedEvent: clientPack is still null");
            return;
        }
        Trace.warning("JsKit", "onAppMessageReceivedEvent: jsonObject is null");
    }

    protected void signalOneWebappOnAppMessageReceived(WebappRunHost target, final String appMessageData, final SignalMessageTypeE signalMessageType) {
        final WebView webView = target.getWebView();
        if (webView != null) {
            runOnAvailableActivityUiThread(target, new Runnable() {
                public void run() {
                    String runString = null;
                    if (signalMessageType.equals(SignalMessageTypeE.Data)) {
                        runString = "javascript:signalNewAppMessageData('" + appMessageData + "')";
                    } else if (signalMessageType.equals(SignalMessageTypeE.Nack)) {
                        runString = "javascript:signalAppMessageNack('" + appMessageData + "')";
                    } else if (signalMessageType.equals(SignalMessageTypeE.Ack)) {
                        runString = "javascript:signalAppMessageAck('" + appMessageData + "')";
                    }
                    if (runString != null) {
                        webView.loadUrl(runString);
                    } else {
                        Trace.warning("JsKit", "signalOneWebappOnAppMessageReceived: runString is null");
                    }
                }
            });
        } else {
            Trace.warning("JsKit", "signalOneWebappOnAppMessageReceived: webView is null (for " + signalMessageType + ")");
        }
    }

    protected void signalOneWebappWebUiBringupOpportunity(final WebUiBringUpOpportunityTypeE types, WebappRunHost target) {
        final WebView webView = target.getWebView();
        if (webView != null) {
            runOnAvailableActivityUiThread(target, new Runnable() {
                public void run() {
                    String dataToSend = null;
                    try {
                        JSONObject jo = new JSONObject();
                        jo.put("uiTypeAllowed", types.name());
                        dataToSend = jo.toString();
                    } catch (Exception e) {
                        Trace.debug("JsKit", "signalOneWebappWebUiBringupOpportunity", e);
                    }
                    webView.loadUrl(dataToSend == null ? "javascript:signalReady()" : "javascript:signalSettingsWebuiLaunchOpportunity('" + dataToSend + "')");
                }
            });
        }
    }

    protected void signalOneWebappOnReady(final String[] pebbleDeviceIdsThatAreReady, WebappRunHost target) {
        final WebView webView = target.getWebView();
        if (webView != null) {
            runOnAvailableActivityUiThread(target, new Runnable() {
                public void run() {
                    String dataToSendAboutPebbleDeviceIds = null;
                    try {
                        JSONObject jo = new JSONObject();
                        JSONArray ja = new JSONArray();
                        if (pebbleDeviceIdsThatAreReady != null) {
                            for (String idstring : pebbleDeviceIdsThatAreReady) {
                                if (idstring != null) {
                                    ja.put(idstring);
                                }
                            }
                            jo.put("pebblesReady", ja);
                            dataToSendAboutPebbleDeviceIds = jo.toString();
                        }
                    } catch (Exception e) {
                        Trace.debug("JsKit", "signalOneWebappOnReady", e);
                    }
                    webView.loadUrl(dataToSendAboutPebbleDeviceIds == null ? "javascript:signalReady()" : "javascript:signalReady('" + dataToSendAboutPebbleDeviceIds + "')");
                }
            });
        }
    }

    protected void signalWebappReady(String[] pebbleDeviceIdsThatAreReady, UUID... targetClientIdsToSignal) {
        if (targetClientIdsToSignal != null && targetClientIdsToSignal.length >= 1) {
            for (UUID targetClientId : targetClientIdsToSignal) {
                WebviewClientPack clientPack;
                WebappRunHost clientRef = null;
                synchronized (this.mWebviewClients) {
                    clientPack = (WebviewClientPack) this.mWebviewClients.get(targetClientId);
                    if (clientPack != null) {
                        try {
                            clientRef = (WebappRunHost) clientPack.mWebviewClient.get();
                        } catch (Exception e) {
                            Trace.debug("JsKit", "signalWebappReady", e);
                        }
                        if (clientRef != null) {
                            signalOneWebappOnReady(pebbleDeviceIdsThatAreReady, clientRef);
                        }
                    }
                }
                synchronized (this.mBuiltinWebviewClients) {
                    clientPack = (WebviewClientPack) this.mBuiltinWebviewClients.get(targetClientId);
                    if (clientPack != null) {
                        try {
                            clientRef = (WebappRunHost) clientPack.mWebviewClient.get();
                        } catch (Exception e2) {
                            Trace.debug("JsKit", "signalWebappReady", e2);
                        }
                        if (clientRef != null) {
                            signalOneWebappOnReady(pebbleDeviceIdsThatAreReady, clientRef);
                        }
                    }
                }
            }
        }
    }

    public void signalWebappUiOpened(UUID webappClientId, UUID... targetClientIdsToSignal) {
        signalWebappUiAction(true, webappClientId, targetClientIdsToSignal);
    }

    public void signalWebappUiClosed(UUID webappClientId, UUID... targetClientIdsToSignal) {
        signalWebappUiAction(false, webappClientId, targetClientIdsToSignal);
    }

    protected void signalWebappUiAction(boolean trueOpenedFalseClosed, UUID webappClientId, UUID... targetClientIdsToSignal) {
        if (webappClientId != null && targetClientIdsToSignal != null && targetClientIdsToSignal.length >= 1) {
            for (UUID targetClientId : targetClientIdsToSignal) {
                WebviewClientPack clientPack;
                WebappRunHost clientRef = null;
                synchronized (this.mWebviewClients) {
                    clientPack = (WebviewClientPack) this.mWebviewClients.get(targetClientId);
                    if (clientPack != null) {
                        try {
                            clientRef = (WebappRunHost) clientPack.mWebviewClient.get();
                        } catch (Exception e) {
                            Trace.debug("JsKit", "signalWebappUiAction", e);
                        }
                        if (clientRef != null) {
                            if (trueOpenedFalseClosed) {
                                signalOneWebappOnUiOpenedAction(webappClientId, clientRef);
                            } else {
                                signalOneWebappOnUiClosedAction(webappClientId, clientRef, retrieveNextAvailableLeftBehindDataForClosedWebapp(webappClientId));
                            }
                        }
                    }
                }
                synchronized (this.mBuiltinWebviewClients) {
                    clientPack = (WebviewClientPack) this.mBuiltinWebviewClients.get(targetClientId);
                    if (clientPack != null) {
                        try {
                            clientRef = (WebappRunHost) clientPack.mWebviewClient.get();
                        } catch (Exception e2) {
                            Trace.debug("JsKit", "signalWebappUiAction", e2);
                        }
                        if (clientRef != null) {
                            if (trueOpenedFalseClosed) {
                                signalOneWebappOnUiOpenedAction(webappClientId, clientRef);
                            } else {
                                signalOneWebappOnUiClosedAction(webappClientId, clientRef, retrieveNextAvailableLeftBehindDataForClosedWebapp(webappClientId));
                            }
                        }
                    }
                }
            }
        }
    }

    protected String retrieveNextAvailableLeftBehindDataForClosedWebapp(UUID webappClientId) {
        String[] dataLeftBehind = JsPseudoIPC.systemInstanceAccess().retrieveNextData(webappClientId.toString());
        if (dataLeftBehind == null || dataLeftBehind.length < 2 || dataLeftBehind[1] == null) {
            return null;
        }
        return new String(dataLeftBehind[1]);
    }

    protected void signalOneWebappOnUiOpenedAction(final UUID webappClientId, WebappRunHost target) {
        final WebView webView = target.getWebView();
        if (webView != null) {
            runOnAvailableActivityUiThread(target, new Runnable() {
                public void run() {
                    webView.loadUrl("javascript:signalWebviewOpenedEvent(\"" + webappClientId.toString() + "\")");
                }
            });
        }
    }

    protected void signalOneWebappOnUiClosedAction(UUID webappClientId, WebappRunHost target, final String stringDataToSendInEvent) {
        final WebView webView = target.getWebView();
        if (webView != null) {
            runOnAvailableActivityUiThread(target, new Runnable() {
                public void run() {
                    String sEnc = Uri.encode(stringDataToSendInEvent.replace("\\", "\\\\"));
                    StringBuilder append = new StringBuilder().append("javascript:signalWebviewClosedEvent('");
                    if (sEnc == null) {
                        sEnc = "";
                    }
                    webView.loadUrl(append.append(sEnc).append("')").toString());
                }
            });
        }
    }

    public void privateFnConfirmReadySignal(String callerIdString, boolean success) {
        UUID callerId = null;
        try {
            callerId = UUID.fromString(callerIdString);
        } catch (Exception e) {
            Trace.debug("JsKit", "privateFnConfirmReadySignal", e);
        }
        privateFnConfirmReadySignal(callerId, success);
    }

    public void privateFnConfirmReadySignal(UUID callerId, boolean success) {
        Trace.verbose("JsKit", "privateFnConfirmReadySignal() callerId = " + callerId + " success = " + success);
        UUID activeWebappUuid = jsKitAccess().currentActiveAppUuid(callerId);
        jsKitAccess().onJsAppReadyCallbackTouch(activeWebappUuid);
        this.mJsAppHeartbeatVerifierTimerTask.compareAndSet(null, new TimerTask() {
            public void run() {
                List<WebviewClientPack> flaggedForReaper = new ArrayList();
                int nProcessedClients = 0;
                synchronized (JsKit.this.mWebviewClients) {
                    for (Entry<UUID, WebviewClientPack> ent : JsKit.this.mWebviewClients.entrySet()) {
                        WebviewClientPack client = (WebviewClientPack) ent.getValue();
                        if (!(client == null || (client.getTempRef() instanceof WebappGenericBaseFragment))) {
                            nProcessedClients++;
                            if (!client.verifyHeartbeatCount()) {
                                flaggedForReaper.add(client);
                            }
                        }
                    }
                    if (nProcessedClients == 0) {
                        cancel();
                        JsKit.jsKitAccess().mJsAppHeartbeatVerifierTimerTask.compareAndSet(this, null);
                        Trace.debug("JsKit", "mJsAppHeartbeatVerifierTimer has no more clients to monitor; TimerTask is cancelled.");
                    }
                }
                for (WebviewClientPack client2 : flaggedForReaper) {
                    JsKit.jsKitAccess().directlyInvokeAppCloseForNoUiApp(client2);
                }
            }
        });
        try {
            TimerTask tt = (TimerTask) this.mJsAppHeartbeatVerifierTimerTask.get();
            if (tt != null) {
                synchronized (this.mJsAppHeartbeatVerifierTimerTask) {
                    this.mJsAppHeartbeatVerifierTimer.schedule(tt, 0, 5000);
                }
            }
        } catch (IllegalStateException e) {
            Trace.debug("JsKit", "mJsAppHeartbeatVerifierTimer already has this timertask scheduled. This is not an error");
        }
        loggerForWebappsExtended(activeWebappUuid, callerId, "++_JS_LIFECYCLE_++:READY-RUNNING");
    }

    public void privateFnHeartbeatPeriodic(String callerIdString) {
        UUID callerId = null;
        try {
            callerId = UUID.fromString(callerIdString);
        } catch (Exception e) {
            Trace.debug("JsKit", "privateFnHeartbeatPeriodic", e);
        }
        privateFnHeartbeatPeriodic(callerId);
    }

    public void privateFnHeartbeatPeriodic(UUID callerId) {
        WebviewClientPack client = jsKitAccess().getWebappInfoByUuid(callerId);
        if (client != null) {
            client.heartbeat();
        }
    }

    public void pong(String callerIdString, String opt) {
        String str;
        String str2 = "JsKit";
        StringBuilder append = new StringBuilder().append("raw-log: pong(); callerIdString = ");
        if (callerIdString == null) {
            str = "";
        } else {
            str = callerIdString;
        }
        Trace.debug(str2, append.append(str).append(" opt = ").append(opt == null ? "" : opt).toString());
        UUID callerId = null;
        try {
            callerId = UUID.fromString(callerIdString);
        } catch (Exception e) {
            Trace.debug("JsKit", "pong", e);
        }
        pong(callerId, opt);
    }

    public void pong(UUID callerId, String opt) {
        String str;
        String chkUuid = null;
        try {
            chkUuid = callerId.toString();
        } catch (Exception e) {
            Trace.debug("JsKit", "pong", e);
        }
        String str2 = "JsKit";
        StringBuilder append = new StringBuilder().append("raw-log: pong(); callerId(UUID) = ");
        if (chkUuid == null) {
            chkUuid = "";
        }
        StringBuilder append2 = append.append(chkUuid).append(" opt = ");
        if (opt == null) {
            str = "";
        } else {
            str = opt;
        }
        Trace.debug(str2, append2.append(str).toString());
        onPongComplete(callerId, opt);
    }

    protected void onPongComplete(UUID uuid, String opt) {
        if (uuid != null) {
            try {
                synchronized (this.mPongSynchroWaitStatusMap) {
                    Object[] existingCvData = (Object[]) this.mPongSynchroWaitStatusMap.remove(uuid);
                    if (existingCvData != null) {
                        Lock cL = accessCWaitLockFromOpaqueCondvData(existingCvData);
                        Condition cV = accessCWaitCondvFromOpaqueCondvData(existingCvData);
                        try {
                            cL.lock();
                            cV.signalAll();
                        } catch (Exception e) {
                            Trace.debug("JsKit", "onPongComplete", e);
                        } finally {
                            cL.unlock();
                        }
                    }
                }
            } catch (Exception e2) {
            }
        }
    }

    public static Lock accessCWaitLockFromOpaqueCondvData(Object[] condvData) {
        try {
            return (Lock) condvData[0];
        } catch (Exception e) {
            Trace.debug("JsKit", "accessCWaitLockFromOpaqueCondvData", e);
            return null;
        }
    }

    public static Condition accessCWaitCondvFromOpaqueCondvData(Object[] condvData) {
        try {
            return (Condition) condvData[1];
        } catch (Exception e) {
            Trace.debug("JsKit", "accessCWaitCondvFromOpaqueCondvData", e);
            return null;
        }
    }

    public static void loggerForWebapps(final UUID uuidOfReferent, final String textToLog) {
        JsThreadPools.MainWorkerThreadsExecutorService().execute(new Runnable() {
            public void run() {
                String safeTextToLog = textToLog == null ? "(null)" : textToLog;
                UUID safeReferentUUID;
                if (uuidOfReferent == null) {
                    safeReferentUUID = new UUID(0, 0);
                } else {
                    safeReferentUUID = uuidOfReferent;
                }
                JsDeveloperConnectionBridge.getInstance().logMessage(safeTextToLog);
            }
        });
    }

    public static void loggerForWebappsExtended(final UUID uuidOfReferent, final UUID uuidOfHostingClientRunHost, final String textToLog) {
        JsThreadPools.MainWorkerThreadsExecutorService().execute(new Runnable() {
            public void run() {
                String extendedDataPrepend = "{'runhost client uuid' = " + (uuidOfHostingClientRunHost == null ? new UUID(0, 0) : uuidOfHostingClientRunHost).toString() + "}:{'webapp uuid' = " + (uuidOfReferent == null ? new UUID(0, 0) : uuidOfReferent).toString() + "}:";
                String safeTextToLog = textToLog == null ? "(null)" : textToLog;
                try {
                    JsDeveloperConnectionBridge.getInstance().logMessage(extendedDataPrepend + " " + safeTextToLog);
                } catch (Throwable e) {
                    Trace.debug("JsKit", e);
                }
                Trace.debug("JsKit", extendedDataPrepend + " " + safeTextToLog);
            }
        });
    }

    public void privateFnSetProxyHtmlLocalStorageValue(String key, String value) {
    }

    public void privateFnResetProxyHtmlLocalStorage() {
    }

    public String localStorageWrite(String callerIdString, String settingName, String settingValue) {
        String str = null;
        if (!(callerIdString == null || settingName == null || settingValue == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    str = JsAppPersistentSettings.writeLocalStoragePreference(callerId, settingName, settingValue);
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "localStorageWrite", e);
            }
        }
        return str;
    }

    public String localStorageRead(String callerIdString, String settingName) {
        String str = null;
        if (!(callerIdString == null || settingName == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    str = JsAppPersistentSettings.readLocalStoragePreference(callerId, settingName, null);
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "localStorageRead", e);
            }
        }
        return str;
    }

    public String localStorageRead(String callerIdString) {
        String str = null;
        if (callerIdString != null) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    str = JsAppPersistentSettings.readLocalStoragePreferences(callerId);
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "localStorageRead", e);
            }
        }
        return str;
    }

    public String localStorageRemove(String callerIdString, String settingName) {
        String str = null;
        if (!(callerIdString == null || settingName == null)) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    str = JsAppPersistentSettings.clearLocalStoragePreference(callerId, settingName);
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "localStorageRemove", e);
            }
        }
        return str;
    }

    public void localStorageClear(String callerIdString) {
        if (callerIdString != null) {
            try {
                UUID callerId = jsKitAccess().currentActiveAppUuid(callerIdString);
                if (callerId != null) {
                    JsAppPersistentSettings.clearLocalStoragePreferences(callerId);
                }
            } catch (Exception e) {
                Trace.debug("JsKit", "localStorageClear", e);
            }
        }
    }

    public static <T> T valueClamp(Comparable<T> low, T val, Comparable<T> high) {
        try {
            if (low.compareTo(val) > 0) {
                return low;
            }
            if (high.compareTo(val) < 0) {
                return high;
            }
            return val;
        } catch (Throwable e) {
            Trace.error("JsKit", e);
        }
    }
}
